How do I close a tkinter window?

Illumination in case of confusion...

def quit(self):
    self.destroy()
    exit()

A) destroy() stops the mainloop and kills the window, but leaves python running

B) exit() stops the whole process

Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.


import tkinter as tk

def quit(root):
    root.destroy()

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

def quit()
    root.quit()

or

def quit()
    root.destroy()

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()?.

Tags:

Python

Tkinter