Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 40 ยท Events and Bindings

Tkinter Timers, Focus and Background Threads

Use after() for timers, debounce and animation, manage keyboard focus and tab order, and run slow work in background threads safely with a queue and polling.

Three event-related topics round out chapter 4: time (timers, debouncing and animation with after), focus (which widget receives the keyboard, and in what order Tab moves) and threads (how to keep long jobs off the interface thread without breaking Tk). The Event Loop explained why they matter; here are the recipes.

Timers with after()

root.after(delay_ms, function, *args) runs function(*args) once, at least delay_ms later, and returns an id. Re-arming from inside the callback makes a repeating timer.

Python
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, font=("Consolas", 40))
label.pack(padx=40, pady=20)

state = {"seconds": 0, "job": None, "running": False}

def tick():
    state["seconds"] += 1
    label.config(text=f"{state['seconds'] // 60:02d}:{state['seconds'] % 60:02d}")
    state["job"] = root.after(1000, tick)

def start():
    if not state["running"]:
        state["running"] = True
        state["job"] = root.after(1000, tick)

def stop():
    state["running"] = False
    if state["job"] is not None:
        root.after_cancel(state["job"])
        state["job"] = None

def reset():
    stop()
    state["seconds"] = 0
    label.config(text="00:00")

label.config(text="00:00")
for text, command in [("Start", start), ("Stop", stop), ("Reset", reset)]:
    tk.Button(root, text=text, command=command, width=8).pack(side="left", padx=6, pady=(0, 16))
root.mainloop()

Always store the id so you can cancel it (before destroying the window, before starting a new timer that would double up, or when the user clicks stop). Starting a timer twice without guarding is the usual cause of "my clock runs twice as fast".

Counting drift

after(1000, tick) is a minimum delay: the real period is 1000 ms plus the callback's runtime plus loop latency. Over hours a clock built by adding one second per tick drifts. The robust approach is to compare against the real clock: store the start time with time.monotonic() and compute elapsed time on each tick, using after only to refresh the display.

Python Stand-in: counting ticks versus using a clock

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.

Animation and debounce

Animation is a self-scheduling after at about 16 ms (60 frames per second) that updates positions a little each time. Keep per-frame work small, move by amounts and not "steps per call" so speed does not depend on frame rate, and stop when the object finishes.

Python
def animate():
    x1, y1, x2, y2 = canvas.coords(ball)
    if x2 >= 400 or x1 <= 0:
        velocity[0] *= -1
    canvas.move(ball, velocity[0], 0)
    root.after(16, animate)

Debounce waits for the user to stop typing before doing expensive work such as a search. On every keystroke you cancel the pending timer and start a new one; only the last one fires.

Python
pending = {"job": None}

def on_key(event):
    if pending["job"]:
        root.after_cancel(pending["job"])
    pending["job"] = root.after(300, run_search)       # 300 ms of silence

entry.bind("<KeyRelease>", on_key)

The model below implements debounce on a list of keystroke times, showing how many searches run with and without it:

Python Stand-in: debounce

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.

Focus and tab order

The focus widget receives keyboard events.

Python
entry.focus_set()                 # start with the cursor in the first field
root.focus_get()                  # which widget has focus now
root.focus_force()               # grab focus for the window (use rarely)
widget.config(takefocus=False)    # skip this widget when tabbing

Tab order follows the order in which widgets were created (and the stacking order). Pressing Tab moves forward; Shift+Tab, back. To fix a wrong order, create widgets in the order you want, or call widget.lift() on them in order. Bind <FocusIn> and <FocusOut> to highlight the active field or validate on leave:

Python
def on_focus_in(event):
    event.widget.config(highlightbackground="#2a9d8f", highlightthickness=2)

def on_focus_out(event):
    event.widget.config(highlightthickness=0)
    validate_field(event.widget)

for field in (name_entry, email_entry):
    field.bind("<FocusIn>", on_focus_in)
    field.bind("<FocusOut>", on_focus_out)

Enter-to-advance (like a data-entry screen) is another common need:

Python
def next_field(event):
    event.widget.tk_focusNext().focus_set()
    return "break"

for field in fields:
    field.bind("<Return>", next_field)

tk_focusNext() and tk_focusPrev() give the next and previous widgets in the tab order.

Threads: running slow work safely

Sleeping or blocking calls freeze the window. For long jobs such as network requests, file processing or heavy computation, use a worker thread, but follow one iron rule: only the main thread may touch Tk widgets. Calling label.config() from another thread may work for a while and then crash or hang, depending on the platform and Tcl build.

The safe design:

  1. The worker thread does the job and puts messages on a queue.Queue.
  2. The main thread polls the queue with after and updates widgets from there.
Python
import queue
import threading
import time
import tkinter as tk

messages = queue.Queue()

def worker():
    for step in range(1, 6):
        time.sleep(1)                      # pretend this is slow
        messages.put(("progress", step * 20))
    messages.put(("done", "Finished!"))

def poll():
    try:
        while True:                        # drain everything that is waiting
            kind, value = messages.get_nowait()
            if kind == "progress":
                bar["value"] = value
            else:
                status.config(text=value)
                button.config(state="normal")
    except queue.Empty:
        pass
    root.after(100, poll)                  # check again in 100 ms

def start():
    button.config(state="disabled")
    status.config(text="Working...")
    bar["value"] = 0
    threading.Thread(target=worker, daemon=True).start()

root = tk.Tk()
from tkinter import ttk
bar = ttk.Progressbar(root, length=240)
bar.pack(padx=20, pady=(20, 8))
status = tk.Label(root, text="Idle")
status.pack()
button = tk.Button(root, text="Start", command=start)
button.pack(pady=12)
poll()
root.mainloop()

daemon=True lets the program exit even if the thread is still running. Never block in poll (use get_nowait, not get()). The queue is thread-safe by design, which is why it is the bridge.

Pyodide in a browser cannot start real threads, so the stand-in simulates the worker by scheduling its steps on a virtual clock. The point of interest is the protocol: producer puts messages, the main loop polls and drains.

Python Stand-in: producer, queue and polling

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.

If you use concurrent.futures.ThreadPoolExecutor, the same rule applies: results come back to the main thread through a queue or by polling future.done() in an after loop. Avoid future.result() on the main thread, because it blocks. For CPU-heavy work in pure Python, use multiprocessing and a Queue the same way, since threads share Python's GIL.

Another option is asyncio: run its loop in a background thread, or call root.after from a small helper that steps the loop. This is more advanced; chapter 8 returns to it in the "patterns" lessons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a Tkinter app keep the id returned by after()?

    after_cancel(id) stops a pending timer, for example when the window closes or the user stops a clock.
  2. 2. How does debounce work in a search box?

    Each key press resets the timer; the search runs only after the user pauses.
  3. 3. Which thread is allowed to update Tkinter widgets?

    Tk is not thread-safe. Worker threads should send results through a queue that the main thread polls.
  4. 4. What determines the Tab key order?

    Focus traversal follows creation order; create widgets in the order you want or use lift() to reorder.

Summary

  • after(ms, func) schedules a timer; keep the id, cancel with after_cancel, and compute elapsed time from a real clock to avoid drift.
  • Animations are self-rescheduling after loops; debounce cancels and restarts a timer on each key.
  • Focus decides who gets key events; tab order follows creation order; FocusIn/FocusOut and tk_focusNext() help build smooth forms.
  • Run slow work in a thread (or process), send results through a queue.Queue, and let the main thread poll it with after and update widgets.
  • Never touch widgets from a worker thread.

Next: Message Boxes: showinfo, askyesno and Friends