Tkinter Designer

← tkinter how-to

Why does my tkinter window freeze or say "Not Responding" during a long task?

Everything in tkinter, redrawing included, happens on one thread inside mainloop(). While a button's command is running (a download, a database query, a time.sleep, a big loop) that thread is busy, so nothing gets drawn and the operating system marks the window "Not Responding". The fix is to run the slow part on a worker thread and hand the result back to tkinter with after():

import threading
import time
import tkinter as tk
from tkinter import messagebox


def slow_task():
    time.sleep(3)  # stand-in for a download, a query, a big loop
    return "Finished"


def on_click():
    button.configure(state="disabled")  # no second job while one runs
    status.configure(text="Working...")
    threading.Thread(target=work, daemon=True).start()


def work():
    # Runs in the background: don't touch widgets in here.
    try:
        result, error = slow_task(), None
    except Exception as e:
        result, error = None, e
    root.after(0, done, result, error)


def done(result, error):
    # Back on tkinter's thread, so updating widgets is safe again.
    button.configure(state="normal")
    if error is not None:
        status.configure(text="")
        messagebox.showerror("Something went wrong", str(error))
    else:
        status.configure(text=result)


root = tk.Tk()
button = tk.Button(root, text="Start", command=on_click)
button.pack(padx=20, pady=(20, 8))
status = tk.Label(root, text="")
status.pack(padx=20, pady=(0, 20))
root.mainloop()

Only touch widgets from the main thread

Tkinter is not thread-safe. Calling label.configure() straight from the worker often seems to work, then fails at random with RuntimeError: main thread is not in main loop or Tcl_AsyncDelete: async handler deleted by the wrong thread, which makes it one of the hardest tkinter bugs to pin down. So the worker only computes; anything visible happens in a function that after runs on tkinter's own thread.

root.after(0, done, result, error) is the usual hand-back, because it only schedules the call. For the strictest version, have the worker put results on a queue.Queue and let the main thread poll it with after every 100 ms, so the worker never calls into tkinter at all.

Showing progress while it runs

The same rule applies to a progress bar: the worker reports a number, and after applies it. Disable the button for the duration as well, or an impatient second click starts a second thread doing the same job.

When there is no way to know how far along the task is, use an indeterminate bar instead: call bar.start() before starting the thread and bar.stop() in the done function, and it animates by itself while the work runs.

from tkinter import ttk

bar = ttk.Progressbar(root, maximum=100)

def work():
    for i, item in enumerate(items):
        process(item)                      # the slow part
        percent = (i + 1) * 100 / len(items)
        root.after(0, lambda p=percent: bar.configure(value=p))

Why calling update() in the loop is the wrong fix

Sprinkling root.update() through a long loop does make the window repaint, which is why it is such a common answer. But it runs every pending event inside your loop, including a second click on the same button, which starts the handler again before the first one has finished. It also does nothing during any single slow call, so the window still hangs for the whole of one requests.get().

When you don't need a thread at all

If the work is many small, quick steps (an animation, a countdown, stepping through a list) there is no need for a thread. Do one step, then schedule the next with after, and the window stays responsive between steps because control goes back to mainloop() each time.

def count_down(n):
    status.configure(text=str(n))
    if n > 0:
        root.after(1000, count_down, n - 1)   # call again in a second

count_down(10)

Closing the window while the task runs

daemon=True is what lets the program exit when the window closes mid-task; without it Python waits for the thread to finish, and the app seems to hang on close. A daemon thread is simply abandoned, though, so a task that writes files should check a threading.Event and stop at a safe point. Python has no way to kill a thread from outside.

stop = threading.Event()

def work():
    for item in items:
        if stop.is_set():
            return          # finish cleanly, files closed
        process(item)

root.protocol("WM_DELETE_WINDOW", lambda: (stop.set(), root.destroy()))

Doing it without the lookup

Select a button and tick Run in background in the inspector. The exported code splits its handler into a click method that disables the button and starts a daemon thread, a _work method for your slow code, and a _done method that runs back on the window's thread and shows any exception in an error box. Choose a progress bar and a status label and it adds a _report helper that updates both safely from the background. It is free and works the same way for plain tkinter, CustomTkinter and ttkbootstrap.

This example is ready to open: change it on the canvas and watch the Python update.

Open this example in the designer →

Related questions