I want to make a window that contains a button that opens another new window while closing the initial window. It sounds simple, but I know that I have to be doing something wrong here as it cannot destroy the initial window when it opens the second one. This is the error I get: _tkinter.TclError: can't invoke "destroy" command: application has been destroyed
and this is the code sample:
from tkinter import *
def openWindow2():
win2 = Tk()
win2.focus()
win2.geometry("1500x880 200 70")
win2.title("window2")
win2.mainloop()
def openWindow1():
win1 = Tk()
win1.geometry("700x700 600 150")
win1.title("window1")
win1.resizable(False, False)
titleFrame = Frame(win1)
titleFrame.pack(side=TOP, pady=25)
Label(titleFrame, text="Welcome", font=("Helvetica", 30)).pack()
def openNewWindow():
openWindow2()
win1.destroy()
openButton = Button(win1, text="New Window", font=("Helvetica", 20), command=openNewWindow)
openButton.pack(pady=5)
win1.mainloop()
openWindow1()
My intentions are to make a sort of portal/launcher/menu window that lets you open other windows (which are more important than it obviously). Again, I know that I did something wrong but I don't know what to do instead. I tried making the initial or second window Toplevel but that didn't work (as I intended). Currently all that "openNewWindow()" does is open the second window but keeps the initial one open (but unfocused) and gives out the aforementioned error.
So, can anyone tell me why this is happening and how to solve it?
CodePudding user response:
I think you need to change to Toplevel() instead of doubling the Tk() instance and then withdraw() the orignal window instead of destroy() since thats where your mainloop() is. You could also bring back the original window then with deiconify(). check this out.
from tkinter import *
def openWindow2():
win2 = Toplevel()
win2.focus()
win2.geometry("1500x880 200 70")
win2.title("window2")
def openWindow1():
win1 = Tk()
win1.geometry("700x700 600 150")
win1.title("window1")
win1.resizable(False, False)
titleFrame = Frame(win1)
titleFrame.pack(side=TOP, pady=25)
Label(titleFrame, text="Welcome", font=("Helvetica", 30)).pack()
def openNewWindow():
openWindow2()
win1.withdraw()
openButton = Button(win1, text="New Window", font=("Helvetica", 20), command=openNewWindow)
openButton.pack(pady=5)
win1.mainloop()
openWindow1()