[Python] How can I run a long-running task in Tkinter without freezing the UI (while keeping...

Discussão em 'Python' iniciado por Stack, Agosto 18, 2025.

  1. Stack

    Stack Membro Participativo

    I’m building a Tkinter app where I visualize sorting algorithms on a Canvas. The problem: whenever I run the sorting function, the entire UI freezes until the function finishes.

    Here’s a simplified version of my code:

    import tkinter as tk
    import time

    def bubble_sort(canvas, data):
    n = len(data)
    for i in range(n):
    for j in range(0, n-i-1):
    if data[j] > data[j+1]:
    data[j], data[j+1] = data[j+1], data[j]
    draw_data(canvas, data)
    time.sleep(0.1) # <-- freezes the UI

    def draw_data(canvas, data):
    canvas.delete("all")
    for i, val in enumerate(data):
    canvas.create_rectangle(i*20, 200-val, (i+1)*20, 200, fill="blue")

    def start_sort():
    bubble_sort(canvas, [5,3,8,4,2])

    root = tk.Tk()
    canvas = tk.Canvas(root, width=200, height=200)
    canvas.pack()

    btn = tk.Button(root, text="Start", command=start_sort)
    btn.pack()

    root.mainloop()


    Issues I face:

    The UI freezes during sorting, and I can’t interact with the window.

    If I try after() instead of sleep, I get confused about how to rewrite the nested loops.

    I’ve seen people suggest using threads, but then I run into errors when updating the Canvas from a thread (since Tkinter isn’t thread-safe).

    What’s the best practice in Tkinter for running long tasks (like sorting) while keeping the GUI responsive?

    Should I restructure the algorithm to work with after() instead of sleep?

    Or is it better to use threads/processes with some kind of queue to update the Canvas?

    Continue reading...

Compartilhe esta Página