Skip to content Skip to sidebar Skip to footer

How Do You Close All Tkinter Windows When Specific Window Closes?

I have this application in Python Tkinter. There is a Python file which is a main menu. When I click an option in the main menu it imports a python file with code that makes a new

Solution 1:

I am assuming that your other scripts have individual instances of Tk(), their own mainloop() and are not under a function, if that is the case, you can have all the code in your files under a function and use Toplevel(), example, file1 should look like

defsomething():
    window=Toplevel()
    #Rest of the code

And similarly file2, after that in your main program you could do something like this

from tkinter import *
import file1, file2

root = Tk()
root.geometry("600x600")

defnewWindowImport():
    file1.something()

defnewWindowImport2():
    file2.something()

newWindow = Button(text="new window", command=newWindowImport)
newWindow.pack()
newWindow2 = Button(text="new window", command=newWindowImport2)
newWindow2.pack()

# Here is there a way so that when I exit it destroys the Main Menu as well as the opened windows
exitBtn = Button(text="Exit", command=root.destroy)

root.mainloop()

You could also let go of the functions and make these changes to have it shorter

newWindow = Button(text="new window", command=file1.something)
newWindow.pack()
newWindow2 = Button(text="new window", command=file2.something)
newWindow2.pack()

The reason for your approach not working would be that each file had it's own mainloop() and hence they couldn't be destroyed when you called root.destroy in the main code.

Also note that I have removed the parentheses () from the command=root.destroy otherwise the it will be called as soon as the program initializes.

EDIT : As also suggested by @martineau in the comments, it's better to use .pack() on the Button instances separately as it provides more flexibility in using the instance later in the program, as opposed to having them hold the value None which is the return from .pack()

Solution 2:

Using Toplevel is the correct way to do this, you need to find out why that is not working and correct it. If you did that this question would solve itself. Also, you need to remove the () from the command, it should be like this:

exitBtn = Button(text="Exit", command=root.destroy)

Post a Comment for "How Do You Close All Tkinter Windows When Specific Window Closes?"