Your Search Bar For Shrewd Tips

How To Close Tkinter Window Automatically


Want a Tkinter window to close on its own after a delay, when a task finishes, or once a countdown reaches zero? The simplest approach is to schedule a callback with Tkinter’s after() method and call destroy() when that callback runs. This lets the application close automatically without freezing the interface. In this guide, you’ll learn how to close a Tkinter window automatically, choose the right delay, handle multiple windows, and avoid common timing and cleanup problems.

The Basic Way to Close a Tkinter Window Automatically

Create your main window, schedule a call to destroy(), and then start the Tkinter event loop with mainloop(). The delay passed to after() is measured in milliseconds.

import tkinter as tk

root = tk.Tk()
root.title("Auto-closing window")

# Close the window after 5 seconds (5000 milliseconds)
root.after(5000, root.destroy)

root.mainloop()

When the program reaches mainloop(), Tkinter continues processing events and keeps the window responsive. After approximately five seconds, the scheduled callback runs and root.destroy() closes the window and its child widgets. Use root.after(5000, root.destroy) rather than adding parentheses after destroy. Passing root.destroy() would call the method immediately instead of scheduling it.

The delay is not a guaranteed precision timer. Tkinter runs callbacks through its event loop, so a busy callback or an unresponsive application can make the window close later than requested. Keep event handlers short to help the timer run on schedule.

How Tkinter’s after() Method Works

The after() method tells Tkinter to run a function after a specified number of milliseconds. It does not pause Python while it waits. Instead, it registers the callback and returns control to the event loop, allowing the window to redraw and respond to clicks and keyboard input in the meantime.

Its common form is widget.after(delay_ms, callback). The callback is a function or method to run, and the delay is a non-negative integer. For instance, root.after(2000, close_window) schedules close_window to run after about two seconds. You can use a named function when the closing action needs additional logic:

import tkinter as tk

def close_window():
    print("Closing the application")
    root.destroy()

root = tk.Tk()
root.after(3000, close_window)
root.mainloop()

You can also pass arguments to a callback by adding them after the function name. For example, root.after(3000, show_message, "Time is up") calls show_message("Time is up") after three seconds. Avoid using time.sleep() in a Tkinter callback to wait before closing. It blocks the event loop, making the window appear frozen until the sleep finishes.

Close a Tkinter Window After a Task Finishes

A fixed delay is useful for a splash screen or temporary notification, but it may not suit a task whose duration varies. In that case, close the window when the task completes. Call destroy() at the end of the task’s completion handler:

import tkinter as tk

def finish_task():
    status_label.config(text="Task complete")
    root.after(1000, root.destroy)

root = tk.Tk()
status_label = tk.Label(root, text="Working...")
status_label.pack(padx=20, pady=20)

root.after(3000, finish_task)
root.mainloop()

This example simulates a task that takes three seconds, displays a completion message, and closes one second later. In a real application, call finish_task() when the operation actually finishes rather than assuming it will take a particular amount of time.

For a quick operation that runs in the main thread, calling root.destroy() after the work is done may be enough. For long-running work, do not perform the entire operation in a button callback or other event handler. A long callback prevents Tkinter from processing redraws and user input. Use a worker thread or another non-blocking approach, then update the interface safely from the main thread.

Create an Automatic Countdown

A countdown gives users a visible indication of when a window will close. The example below updates a label once per second and destroys the window when the counter reaches zero:

import tkinter as tk

def update_countdown():
    global seconds_left

    if seconds_left <= 0:
        root.destroy()
        return

    countdown_label.config(
        text=f"This window will close in {seconds_left} seconds"
    )
    seconds_left -= 1
    root.after(1000, update_countdown)

root = tk.Tk()
seconds_left = 5

countdown_label = tk.Label(root, font=("Arial", 14))
countdown_label.pack(padx=20, pady=20)

update_countdown()
root.mainloop()

The first call to update_countdown() displays the initial value. Each later call schedules another update with after(1000, update_countdown). When the counter reaches zero, the function closes the window and returns without scheduling another callback.

For larger applications, store the countdown value on an application class instead of using a global variable. Also consider changing the message to explain why the window will close and whether the user can cancel the countdown.

Close a Toplevel Window Automatically

Tkinter applications can have secondary windows created with tk.Toplevel. To close just a secondary window, call destroy() on that window rather than on the root window. Destroying the root usually closes the entire application, including its other windows.

import tkinter as tk

root = tk.Tk()
root.title("Main window")

popup = tk.Toplevel(root)
popup.title("Temporary popup")
tk.Label(popup, text="This popup closes in 4 seconds").pack(padx=20, pady=20)

popup.after(4000, popup.destroy)

root.mainloop()

Because the callback targets popup, the secondary window closes after four seconds while the main window remains open. This approach is useful for status dialogs, brief alerts, and temporary instructions. If you create several secondary windows, schedule a separate callback on each window you want to close.

Use quit() or destroy()?

destroy() removes a Tkinter window and its widgets. Use it when you want the window to close. Calling root.destroy() normally ends the application’s Tk event loop as well, because the root window no longer exists.

quit() has a different purpose: it stops the current mainloop(), but it does not destroy the window. The window may remain visible, and the application can continue running other Python code. For an automatically closing application, root.after(delay, root.destroy) is usually the clearer choice. Use quit() when you specifically need to leave the event loop and then perform additional work before deciding whether to destroy the window.

Cancel or Replace a Scheduled Close

Sometimes users should be able to keep a window open. The identifier returned by after() lets you cancel a callback before it runs. Save that identifier, then pass it to after_cancel() if the user takes an action that should stop the automatic close.

import tkinter as tk

def keep_open():
    root.after_cancel(close_job)
    status_label.config(text="The automatic close was cancelled")

root = tk.Tk()
status_label = tk.Label(root, text="This window closes in 10 seconds")
status_label.pack(padx=20, pady=10)

keep_button = tk.Button(root, text="Keep open", command=keep_open)
keep_button.pack(pady=10)

close_job = root.after(10000, root.destroy)
root.mainloop()

In this example, clicking the button cancels the scheduled close. In a more complete program, set close_job to None after cancellation and check that it still contains a valid callback identifier before calling after_cancel(). This helps prevent errors if the timer has already fired or has been cancelled elsewhere.

Handle Window Closing and Cleanup

Closing a window automatically can involve more than removing it from the screen. Your application may need to save data, stop a timer, release a resource, or ask the user to confirm. Use Tkinter’s protocol() method to customize what happens when a user clicks the window’s close button. The same cleanup function can be used by the automatic timer:

import tkinter as tk

def close_application():
    # Save settings or release resources here
    root.destroy()

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", close_application)
root.after(10000, close_application)
root.mainloop()

Now the close button and the ten-second timer both call close_application(). This keeps your cleanup logic in one place. If cleanup takes a long time, avoid blocking the event loop; complete the necessary work efficiently or move suitable work off the main thread.

Common Mistakes to Avoid

  • Calling the callback immediately: Use root.after(5000, root.destroy), not root.after(5000, root.destroy()). The latter destroys the window before after() can schedule anything.
  • Using seconds instead of milliseconds: A delay of five seconds is 5000, not 5. A value of 5 schedules the callback after roughly five milliseconds.
  • Blocking the event loop: Avoid time.sleep() in GUI callbacks. Schedule future work with after() so the interface can continue responding.
  • Destroying the wrong window: Call popup.destroy() to close one Toplevel. Call root.destroy() only when you intend to close the main application.
  • Scheduling updates after a window is gone: A repeating countdown should stop scheduling callbacks once it closes. Keep track of timer identifiers if you need to cancel pending callbacks during cleanup.
  • Updating Tkinter directly from a worker thread: Tkinter is designed to be controlled from its main thread. Have background work report results to the main thread before changing widgets or closing the window.

Frequently Asked Questions

How do I close a Tkinter window after five seconds? Schedule its destruction with root.after(5000, root.destroy). The number is in milliseconds, so 5000 equals five seconds.

Can I close a window automatically without freezing it? Yes. Use after() rather than time.sleep(). Tkinter’s event loop remains available to handle user input and redraw the window while it waits.

How do I close only a popup window? Call popup.after(delay_ms, popup.destroy) on the Toplevel instance. This closes the popup without destroying the root window.

Why is my Tkinter window not closing? Check that you passed the callback without calling it, used milliseconds for the delay, and scheduled the callback before the relevant event loop ends. Also verify that you are destroying the correct window.

Conclusion

The standard way to close a Tkinter window automatically is to schedule destroy() with after(). Use a delay in milliseconds for timed popups, call the close function when a task completes for variable-length work, and update a label if users need a countdown. For secondary windows, schedule destruction on the appropriate Toplevel. Keep callbacks responsive, cancel timers when necessary, and centralize cleanup so both automatic and manual closing behave consistently.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →