Knowing how to close a Tkinter window properly is an essential part of building a reliable Python application. Whether you want to close the main window, add a custom Exit button, respond to the window’s X button, or shut down several windows at once, Tkinter provides a few straightforward options. The right method depends on whether you want to end the entire application or close only one window.
This guide explains how to close Tkinter using destroy() and quit(), how to handle the window close button, and how to safely clean up resources before the application exits. The examples use Python’s built-in tkinter module and can be adapted to most desktop projects.
The simplest way to close a Tkinter window
For most applications, the simplest way to close a Tkinter window is to call its destroy() method. This removes the window and its child widgets, and it ends the Tkinter event loop when the destroyed window is the application’s root window.
import tkinter as tk
root = tk.Tk()
root.title("My Tkinter App")
close_button = tk.Button(root, text="Close", command=root.destroy)
close_button.pack(padx=20, pady=20)
root.mainloop()
When the user clicks the button, root.destroy() closes the application window. The call to mainloop() keeps the interface responsive until the window is destroyed. Once the root window is gone, the event loop returns and the Python script can continue or finish.
Use destroy() when you want to close a particular window and remove its widgets. It is usually the best choice for an Exit button in a simple Tkinter application.
How to close Tkinter with an Exit button
An Exit button can call a function that closes the root window. Using a named function is useful when you want to perform additional actions, such as saving data or asking the user to confirm before the program exits.
import tkinter as tk
def close_app():
root.destroy()
root = tk.Tk()
root.title("Example App")
exit_button = tk.Button(root, text="Exit", command=close_app)
exit_button.pack(padx=20, pady=20)
root.mainloop()
Notice that the button’s command is set to close_app, not close_app(). Tkinter expects a function reference that it can call when the button is clicked. Adding parentheses would call the function immediately while the interface is being created.
If the function needs arguments, use a lambda function or another wrapper:
exit_button = tk.Button(
root,
text="Exit",
command=lambda: close_app("button")
)
For a basic application, calling root.destroy() directly is perfectly fine. A dedicated function becomes more helpful as your shutdown process grows.
How to handle the window’s X button
Users often close a desktop application by clicking the X in the window’s title bar. Tkinter normally destroys the root window when the user does this. You can override that default behavior with the protocol() method, which lets you decide what should happen when the window receives a close request.
import tkinter as tk
def close_app():
print("Closing the application")
root.destroy()
root = tk.Tk()
root.title("Example App")
root.protocol("WM_DELETE_WINDOW", close_app)
root.mainloop()
WM_DELETE_WINDOW is the standard window-manager event for a user-requested close. Connecting it to your own function gives you a chance to save information, stop background tasks, or display a confirmation dialog before destroying the window.
Set the protocol on the specific window you want to control. For a single-window application, that is usually the root window. For a secondary window, call protocol() on that window instead.
Ask for confirmation before closing
If closing the application could cause a user to lose unsaved work, show a confirmation dialog. Tkinter’s messagebox module includes askyesno(), which returns True if the user chooses Yes and False otherwise.
import tkinter as tk
from tkinter import messagebox
def confirm_close():
answer = messagebox.askyesno(
"Exit",
"Are you sure you want to close the application?"
)
if answer:
root.destroy()
root = tk.Tk()
root.title("Example App")
root.protocol("WM_DELETE_WINDOW", confirm_close)
exit_button = tk.Button(root, text="Exit", command=confirm_close)
exit_button.pack(padx=20, pady=20)
root.mainloop()
Both the title-bar X button and the Exit button now use the same function, so the application behaves consistently. If the user selects No, the function ends without destroying the window, and the application remains open.
For an application with editable data, the confirmation function can first check whether anything has changed. You might prompt only when there are unsaved edits, rather than asking every time the user closes the window.
What is the difference between destroy() and quit()?
The two Tkinter methods most commonly associated with closing an application are destroy() and quit(). They are related, but they do different things.
-
destroy()destroys a window and its child widgets. Destroying the root window normally ends the application’s Tkinter event loop. -
quit()tells the current Tkinter event loop to stop. It does not, by itself, destroy the windows or widgets.
For a typical Exit button, root.destroy() is the clearest choice. If you call only root.quit(), the window may remain visible even though mainloop() has stopped processing events. That can make the application appear frozen.
quit() can be useful in more specialized situations, such as when you need to stop a running event loop but still want to keep the Tkinter objects available for further work. For ordinary application shutdown, destroy the root window instead.
Also avoid using Python’s exit() or sys.exit() as a replacement for Tkinter window management. Those functions stop Python execution, but they do not provide the same window-specific cleanup behavior. Use Tkinter’s window methods to close the interface cleanly.
How to close a secondary Tkinter window
A Tkinter application can have a root window and one or more additional windows. Additional top-level windows are usually created with Toplevel. To close one of these windows while leaving the main application open, call destroy() on that specific window.
import tkinter as tk
def open_window():
window = tk.Toplevel(root)
window.title("Secondary Window")
close_button = tk.Button(
window,
text="Close This Window",
command=window.destroy
)
close_button.pack(padx=20, pady=20)
root = tk.Tk()
root.title("Main Window")
open_button = tk.Button(root, text="Open Window", command=open_window)
open_button.pack(padx=20, pady=20)
root.mainloop()
Here, clicking Close This Window destroys only the secondary window. The root window and its event loop remain active. If you call root.destroy() instead, the main application closes along with its child windows.
You can also give a secondary window its own close handler:
window.protocol("WM_DELETE_WINDOW", window.destroy)
This is useful when a secondary window needs special behavior, such as confirmation or a cleanup step, when its title-bar X button is clicked.
Close Tkinter after a delay
To close a Tkinter window after a delay, use the after() method. It schedules a function to run after a specified number of milliseconds without blocking the interface.
import tkinter as tk
root = tk.Tk()
root.title("Temporary Window")
root.after(5000, root.destroy)
root.mainloop()
This example closes the window after 5,000 milliseconds, or five seconds. The window stays responsive while the timer counts down. Avoid using time.sleep() in the main Tkinter thread to create a delay, because it blocks the event loop and can make the application unresponsive.
You can also schedule a named function if you need to prepare for shutdown:
def close_later():
print("The timer has finished")
root.destroy()
root.after(5000, close_later)
Clean up resources before closing
Before destroying the root window, you may need to save a file, stop a timer, or release another resource. Put that work in the function that handles shutdown, then destroy the window when cleanup is complete.
def close_app():
save_settings()
root.destroy()
root.protocol("WM_DELETE_WINDOW", close_app)
Make sure cleanup functions can finish reliably. If saving can fail, handle the error and decide whether the application should stay open or close anyway. For example, you can show an error message and let the user return to the application to resolve the problem.
For scheduled callbacks created with after(), keep the callback identifier if you may need to cancel the timer:
timer_id = root.after(10000, do_something)
def close_app():
root.after_cancel(timer_id)
root.destroy()
Canceling callbacks that are no longer needed can prevent unwanted work during shutdown. For more complex applications, keep track of active timers and other background resources so that your close handler can stop them deliberately.
Closing Tkinter when using threads
If your application uses a background thread, closing the Tkinter window does not automatically stop that thread. A non-daemon thread can keep the Python process running after the window is gone. Use a thread-safe signal, such as a threading.Event, to tell background work to stop.
import tkinter as tk
import threading
stop_event = threading.Event()
def close_app():
stop_event.set()
root.destroy()
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", close_app)
root.mainloop()
The worker function should periodically check stop_event.is_set() and exit when it receives the signal. Avoid updating Tkinter widgets directly from a worker thread; Tkinter interface updates should generally happen on the main thread, often through a scheduled callback.
For an application without background threads, you do not need this extra coordination. Start with a simple close handler and add shutdown signaling only when your program actually has work running in the background.
Common mistakes when closing a Tkinter app
-
Calling a button function immediately: Use
command=close_app, notcommand=close_app(), unless you are deliberately assigning the function’s return value. -
Using
quit()when you mean to destroy the window: Stopping the event loop alone may leave the window visible. Usedestroy()for normal shutdown. -
Destroying the wrong window: Call
window.destroy()to close a secondary window, androot.destroy()to close the main application. -
Blocking the event loop: Avoid long-running work or
time.sleep()in the main thread. Useafter()for delays and appropriate background work for long tasks. -
Forgetting the title-bar close event: If you need confirmation or cleanup, connect your handler with
root.protocol("WM_DELETE_WINDOW", handler). - Assuming threads stop automatically: Signal background tasks to finish before the application exits.
Conclusion
For most Python applications, the best way to close Tkinter is to call root.destroy(). Assign it to an Exit button’s command to close the window from the interface, or use root.protocol("WM_DELETE_WINDOW", handler) to control what happens when a user clicks the title-bar X button.
Use window.destroy() to close a secondary window without ending the whole application, and reserve quit() for cases where you specifically need to stop the event loop without immediately destroying the widgets. If your app has unsaved data, timers, or background threads, add a close handler that confirms the user’s choice and completes cleanup before destroying the root window. These patterns make it easy to close a Tkinter window cleanly and predictably.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.