Matt Gregory Matt Gregory - 7 months ago 68
Python Question

Close a tkinter window?

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?

Answer
root.quit()

Above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy()

While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop().

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

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

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