Scheduling actions
A basic technique to prevent blocking the main thread in Tkinter is scheduling an action that will be invoked after a timeout has elapsed.
In this recipe, we will take a look at how to implement this with Tkinter using the after()
method, which can be called from all Tkinter widget classes.
Getting ready
The following code shows a straightforward example of how a callback can block the main loop.
This application consists of a single button that gets disabled when it is clicked, waits 5 seconds, and is enabled again. A trivial implementation would be the following one:
import time import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.button = tk.Button(self, command=self.start_action, text="Wait 5 seconds") self.button.pack(padx=20, pady=20) def start_action(self): self.button.config(state=tk.DISABLED) time.sleep(5) self.button.config(state=tk.NORMAL) if __name__...