Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 40 ยท Getting Started

The Tkinter Event Loop Explained

Understand how Tkinter's mainloop works, why long tasks freeze a window, and how callbacks, after() timers and update_idletasks() keep an interface responsive.

A command-line program runs from the first line to the last. A GUI program does not: after setup it sits and waits. When something happens (a click, a key press, a timer, a request to redraw) Tk calls the function you attached to that event, then goes back to waiting. The waiting loop is mainloop(), and understanding it explains nearly every beginner problem: frozen windows, delayed updates, and code that "runs too early".

What mainloop does

Conceptually, mainloop() is:

Python
while the_window_exists:
    event = wait_for_next_event()
    run_the_callbacks_for(event)
    redraw_whatever_changed()

There is one thread doing all of this. While one of your callbacks is running, no other event is processed and nothing is redrawn. That single fact is the key to the rest of the lesson.

flowchart LR
  A["Wait for event"] --> B["Event arrives<br/>(click, key, timer)"]
  B --> C["Run your callback"]
  C --> D["Process redraws<br/>(idle tasks)"]
  D --> A

The loop alternates between waiting, running one callback and redrawing. A slow callback delays everything that follows.

A working model of the loop

The stand-in below is a miniature event loop with a queue of events, a table of handlers and a virtual clock. It is not Tk, but it has the same moving parts, which makes the behaviour visible and testable.

Python Stand-in: a tiny event loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the tick handler schedules its own next call. That pattern, a callback re-arming itself with after(), is how Tkinter does animation, clocks and polling. You will use it constantly.

Why long tasks freeze the window

Suppose a button callback takes five seconds:

Python
import time
import tkinter as tk

def slow():
    status.config(text="Working...")    # queued, but not drawn yet!
    time.sleep(5)                       # the loop is blocked here
    status.config(text="Done")

root = tk.Tk()
status = tk.Label(root, text="Idle")
status.pack(padx=40, pady=10)
tk.Button(root, text="Start", command=slow).pack(pady=10)
root.mainloop()

Click Start and the window appears dead for five seconds: it cannot repaint, move normally or be closed. Worse, "Working..." never shows, because the label's new text is drawn during the redraw step that happens after the callback returns, and by then the text is already "Done".

The stand-in below counts how many times the loop could have redrawn while a callback blocks it.

Python Stand-in: a blocked loop cannot redraw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three ways to keep the interface alive

1. Break the work into small steps with after(). Do a little, schedule the next piece, return to the loop. This is the standard fix for work that is mostly quick.

Python
def process(items, index=0):
    if index >= len(items):
        status.config(text="Done")
        return
    handle(items[index])                          # one small unit
    status.config(text=f"{index + 1}/{len(items)}")
    root.after(1, process, items, index + 1)      # yield to the loop

2. Call update_idletasks() inside the work to force a redraw. It is a quick fix for progress text, but the window still cannot respond to clicks, so use it sparingly.

3. Use a background thread for genuinely slow things such as downloads, and send results back to the main thread through a queue (see Timers, Focus and Threads). Tkinter widgets must only be touched from the thread that created them.

Here is approach 1 expressed in the mini-loop style, processing 10 items in chunks of 3 and letting a click sneak in between chunks.

Python Stand-in: chunked work lets events through

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The click is handled in the middle of the job because each chunk ends quickly. With one 10-item callback it would have waited until the end.

after, after_idle and after_cancel

Call Meaning
root.after(ms, func, *args) Run func(*args) once after at least ms milliseconds; returns an id
root.after_idle(func, *args) Run when the loop has nothing else to do
root.after_cancel(id) Cancel a scheduled call that has not run yet

The delay is a minimum, not a promise: if another callback is busy at that moment, yours waits. after(0, f) is a handy way of saying "run f as soon as the current callback is finished".

Always keep the id if you may cancel, for example when a window closes while a timer is pending:

Python
def tick():
    global timer_id
    clock.config(text=time.strftime("%H:%M:%S"))
    timer_id = root.after(1000, tick)

def on_close():
    root.after_cancel(timer_id)
    root.destroy()

Common beginner mistakes

  • Calling the function instead of passing it. command=do_work() runs do_work immediately and gives Tk its return value; write command=do_work.
  • while True: loops in a callback. They never return control to Tk. Use after() instead.
  • time.sleep() in a callback. It blocks the loop; use after().
  • Code after mainloop() expecting to run while the window is open. It runs only after the window closes.
  • Updating widgets from another thread. Tk is not thread-safe; use a queue plus after() polling.

Your own program does not have to subclass anything, but as it grows, an object-oriented layout keeps state and callbacks together. That is the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does time.sleep(5) inside a button callback freeze the window?

    Tkinter runs callbacks in the event loop's thread. While your callback blocks, there are no redraws and no new events are handled.
  2. 2. What is the correct way to run tick() again after one second from inside tick()?

    after(ms, func) schedules the function. Passing tick() would call it immediately instead.
  3. 3. What does root.after_cancel(id) do?

    after() returns an id, and after_cancel(id) removes that pending call.
  4. 4. When does code written after root.mainloop() run?

    mainloop() blocks until the main window is destroyed or quit() is called.

Summary

  • mainloop() is a single-threaded loop: wait, run one callback, redraw, repeat.
  • Every callback must return quickly; sleeping or long loops freeze the interface.
  • Use after() for timers and animation, and for splitting long work into chunks.
  • update_idletasks() forces a redraw; threads need a queue to hand results back.
  • Pass functions to command= without parentheses.

Next: Structuring Programs with Classes