Fix Python – How do I close a tkinter window?

Question

Asked By – Matt Gregory

How do I end a Tkinter program? Let’s say I have this code:

from Tkinter import *

def quit():
    # code to exit

root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()

How should I define the quit function to exit my application?

Now we will see solution for issue: How do I close a tkinter window?


Answer

You should use destroy() to close a Tkinter window.

from Tkinter import * 
#use tkinter instead of Tkinter (small, not capital T) if it doesn't work
#as it was changed to tkinter in newer Python versions

root = Tk()
Button(root, text="Quit", command=root.destroy).pack() #button to close the window
root.mainloop()

Explanation:

root.quit()

The above line just bypasses the root.mainloop(), i.e., root.mainloop() will still be running in the background if quit() command is executed.

root.destroy()

While destroy() command vanishes out root.mainloop(), i.e., root.mainloop() stops. <window>.destroy() completely destroys and closes the window.

So, if you want to exit and close the program completely, you should use root.destroy(), as it stops the mainloop() and destroys the window and all its widgets.

But if you want to run some infinite loop and don’t want to destroy your Tkinter window and want to execute some code after the root.mainloop() line, you should use root.quit(). Example:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

See What is the difference between root.destroy() and root.quit()?.

This question is answered By – aki92

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0