Trying to fix tkinter GUI freeze-ups (using threads)

You’ll need two functions: the first encapsulates your program’s long-running work, and the second creates a thread that handles the first function. If you need the thread to stop immediately if the user closes the program while the thread is still running (not recommended), use the daemon flag or look into Event objects. If you don’t want the user to be able to call the function again before it’s finished, disable the button when it starts and then set the button back to normal at the end.

import threading
import tkinter as tk
import time

class App:
    def __init__(self, parent):
        self.button = tk.Button(parent, text="init", command=self.begin)
        self.button.pack()
    def func(self):
        '''long-running work'''
        self.button.config(text="func")
        time.sleep(1)
        self.button.config(text="continue")
        time.sleep(1)
        self.button.config(text="done")
        self.button.config(state=tk.NORMAL)
    def begin(self):
        '''start a thread and connect it to func'''
        self.button.config(state=tk.DISABLED)
        threading.Thread(target=self.func, daemon=True).start()

if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Leave a Comment