Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 40 ยท Packaging and Patterns

Threads and Background Work in Tkinter (queue and after)

Run slow tasks without freezing a Tkinter window: use a worker thread, send results through queue.Queue, poll with after(), support cancel and progress.

Sooner or later a button handler has to do something slow: download a file, scan a folder, call an API, crunch a data set. If you do it inside the handler, the window freezes until it finishes. The user cannot move it, the progress bar does not move, and the operating system may label it "Not responding".

The solution is to do the slow work in a worker thread and keep the main thread free for the GUI. There is one strict rule: only the main thread may touch widgets. Tkinter is not thread-safe, so a worker must hand its results to the main thread, usually through a queue.Queue that the main thread polls with after().

All threaded code is read-only in this lesson: the in-browser runner for Python cannot start threads, and the window code needs a display anyway. The runnable blocks reproduce the same queue protocol with a cooperative worker, so you can run, inspect and test the message flow.

The freeze, again

Python
def fetch():
    result = slow_download()          # takes 5 seconds
    label.config(text=result)

During the five seconds nothing else happens: no redraws, no clicks. Short delays can be spread out using after (Canvas Animation with after()), but a call that blocks (network, a long calculation, time.sleep) cannot be chopped up. It needs another thread.

Worker thread plus queue

Python
import queue
import threading
import time
import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Worker")
        self.messages = queue.Queue()
        self.worker = None
        self.cancel_flag = threading.Event()

        self.bar = ttk.Progressbar(self, maximum=100, length=260)
        self.bar.pack(padx=20, pady=(20, 8))
        self.status = ttk.Label(self, text="Idle")
        self.status.pack()
        self.start_btn = ttk.Button(self, text="Start", command=self.start)
        self.start_btn.pack(pady=8)
        self.cancel_btn = ttk.Button(self, text="Cancel", command=self.cancel_flag.set, state="disabled")
        self.cancel_btn.pack()

    def start(self):
        if self.worker and self.worker.is_alive():
            return
        self.cancel_flag.clear()
        self.start_btn.state(["disabled"])
        self.cancel_btn.state(["!disabled"])
        self.worker = threading.Thread(target=self.work, daemon=True)
        self.worker.start()
        self.after(50, self.poll)

    def work(self):                                  # runs in the worker thread
        for step in range(1, 101):
            if self.cancel_flag.is_set():
                self.messages.put(("cancelled", None))
                return
            time.sleep(0.03)                         # pretend work
            self.messages.put(("progress", step))
        self.messages.put(("done", "Finished 100 steps"))

    def poll(self):                                  # runs in the main thread
        try:
            while True:
                kind, value = self.messages.get_nowait()
                if kind == "progress":
                    self.bar["value"] = value
                    self.status.config(text=f"{value}%")
                elif kind in ("done", "cancelled"):
                    self.status.config(text=value or "Cancelled")
                    self.start_btn.state(["!disabled"])
                    self.cancel_btn.state(["disabled"])
                    return                           # stop polling
        except queue.Empty:
            pass
        self.after(50, self.poll)

App().mainloop()

Pressing Start fills the progress bar over about three seconds while the window stays fully responsive; Cancel stops it early and the status reads "Cancelled". The pieces:

  • work runs in the thread and never touches a widget. It only calls self.messages.put(...), which is thread-safe.
  • poll runs in the main thread through after(50, ...), drains all waiting messages with get_nowait(), updates widgets, and re-schedules itself unless the job is finished.
  • threading.Event is a safe flag for cancel: the worker checks is_set() at convenient points. Never try to kill a thread.
  • daemon=True lets the program exit even if the thread is still running.
  • The Start button is disabled during a run, so users cannot start two workers.

The golden rule

Worker thread Slow work, no widgets
Queue put() results safely
Main thread after() polls, updates widgets

Never call widget methods from a worker.

1 / 2

The same protocol, runnable

The stand-in below is not threading. A generator plays the role of the worker (each yield is a moment when it hands control back), and a loop plays the role of the polling after callback. The messages and the order are the same as in the threaded version, and the cancel flag works the same way.

Python Stand-in: worker, queue and polling 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.

The normal run ends with the bar at 100 and "Finished 10 steps". In the cancelled run the worker notices the flag on its next step and reports cancelled, so the bar stays where it was.

Reporting errors from the worker

An exception inside a thread does not reach the main thread. It prints a traceback to the console and the thread ends; the GUI waits forever. Always wrap the body of the worker and send the failure as a message:

Python
def work(self):
    try:
        data = download(self.url)
        self.messages.put(("done", data))
    except Exception as exc:
        self.messages.put(("error", str(exc)))

The polling code then shows messagebox.showerror from the main thread when it receives "error". The message types of a mature app are a small protocol: progress, result, error, done.

Python Stand-in: turning an exception into a message

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.

Simpler options

  • after chunks. If the work can be sliced (process 100 rows per tick), a generator plus after(1, step) keeps everything in one thread and avoids races. This is the easiest correct solution for CPU work that is not huge.
  • concurrent.futures.ThreadPoolExecutor. future = pool.submit(fn) returns a Future; poll future.done() from after and read future.result() (which re-raises the worker's exception in the main thread, a nice property).
  • asyncio. Possible, but Tkinter and asyncio each want their own event loop. The practical bridge is running asyncio in a worker thread and using the same queue. Do not start with this.
  • multiprocessing. For heavy CPU work (the GIL limits threads), use ProcessPoolExecutor and poll the future the same way. Guard the entry point with if __name__ == "__main__":, or every child process opens a new window.

Event-based notification

Instead of polling, a worker can generate a virtual event: root.event_generate("<<WorkDone>>", when="tail"). Calling event_generate from a worker is often done in practice and works on most platforms, but it is technically not guaranteed to be thread-safe; the queue with after polling is the pattern with no caveats, and it is the one to recommend.

Common mistakes

  • Updating a label or progress bar directly from the thread. This works "most of the time" and then crashes mysteriously.
  • Letting the user press Start twice and getting two workers writing to the same queue.
  • Forgetting daemon=True and wondering why the Python process stays alive after the window closes.
  • Polling too often (after(1)) and wasting CPU, or too rarely (after(2000)) and making the progress bar jumpy. 30 to 100 ms is a good range.
  • Ignoring exceptions in the worker.
  • Using thread.join() in a button handler: it blocks the GUI exactly like the slow function did.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which thread may call widget methods such as label.config?

    Tkinter is not thread-safe; workers should send messages for the main thread to display.
  2. 2. What is the role of after(50, self.poll) in the threaded app?

    The polling callback drains queue.Queue messages in the main thread.
  3. 3. How should a worker be asked to stop?

    Cooperative cancellation with a flag is the safe way; Python cannot kill a thread.
  4. 4. What happens to an uncaught exception in a worker thread?

    Catch exceptions in the worker and send an error message through the queue.

Summary

  • Never block the main thread; run slow work in a worker thread.
  • Workers must not touch widgets; they put messages on a queue.Queue.
  • The main thread polls with after, drains the queue and updates the GUI.
  • Use a threading.Event for cancel, disable Start while running, and report errors as messages.
  • For slicing work in one thread, a generator with after is simpler.

Next: Packaging with PyInstaller