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?
Apart from the issues mentioned by the other answer, there is another issue that if the user closes the toplevel window using the close button in the title bar, the main window will not be restored. Use
.protocol("WM_DELETE_WINDOW", ...)
to fix this issue: