from tkinter import *
from tkinter import ttk
import tkinter as tk
style = ttk.Style()
def main():
global MainMenu
global style
MainMenu = Toplevel()
MainMenu.title('Rubiks Cube Solver') # Creates a window with the title 'Rubiks Cube Solver' that is 640x480 and with a gray background
MainMenu.geometry('640x480')
MainMenu.config(bg='gray')
style.configure('W.TButton', font=('Consolas', 25), foreground = 'black') # Style for the buttons
Label(MainMenu, text='Rubiks Cube Solver', font=('Consolas', 40, 'bold'), bg='gray').pack() # Shows a title 'Rubiks Cube Solver'
timerbtn = ttk.Button(MainMenu, text='Timer', style='W.TButton')
timerbtn.place(relx=0.5, rely=0.7, anchor=CENTER) # Creates a button and anchors it to the center
solverbtn = ttk.Button(MainMenu, text='Solver', style='W.TButton')
solverbtn.place(relx=0.5, rely=0.5, anchor=CENTER)
databasebtn = ttk.Button(MainMenu, text='Database', style='W.TButton', command=maindatabase)
databasebtn.place(relx=0.5, rely=0.3, anchor=CENTER)
def maindatabase():
MainMenu.withdraw()
DataMenu = Toplevel(MainMenu)
DataMenu.title('Database Viewer') # Creates a window with the title 'Database Viewer' that is 640x480 and with a gray background
DataMenu.geometry('640x480')
DataMenu.config(bg='gray')
Label(DataMenu, text='Database Viewer', font=('Consolas', 40, 'bold'), bg='gray').pack() # Shows a title 'Database Viewer'
searchbtn = ttk.Button(DataMenu, text='Search', style='W.TButton')
searchbtn.place(relx=0.5, rely=0.5, anchor=CENTER) # Creates a button and anchors it to the center
fullbtn = ttk.Button(DataMenu, text='Full View', style='W.TButton')
fullbtn.place(relx=0.5, rely=0.6, anchor=CENTER)
backbtn = ttk.Button(DataMenu, text='Back', command=lambda:[DataMenu.destroy(), MainMenu.deiconify()])
backbtn.place(relx=0.9, rely=0.3, anchor=CENTER)
if __name__ == "__main__":
main()`
When this code is run, it opens the desired main menu and a small white window called Tk.
When I define MainMenu = Tk() instead of Toplevel(), none of my buttons have any styling. If I put the styling in the main() function, then the second window has no button styling. Where am I going wrong?
There are two issues in this code example.
In tkinter, it is a good practice to create one "Main Window"
Tk(), and then you can use as many "Dialogs"Toplevel()as you want."Style"
ttk.Style()component requires the "Main Window"Tk()to already be created, if it's not, like in your case, "Style"ttk.Style()creates its own "Main Window"Tk(), and that is the reason you have two windows in your example.Quick Solution:
MainMenu = Toplevel()toMainMenu = Tk(), and addMainMenu.mainloop()at the end of themain()functionstyle = ttk.Style(), and add it to themain()function right after theMainMenu = Tk()Personal Recommendation: (OOP approach)