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?
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()
The above line just bypasses the
root.mainloop() will still be running in the background if
quit() command is executed.
destroy() command vanishes out
<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
from Tkinter import * def quit(): global root root.quit() root = Tk() while True: Button(root, text="Quit", command=quit).pack() root.mainloop() #do something