How to do it...

The after() method allows you to register a callback that is invoked after a delay expressed in milliseconds within Tkinter's main loop. You can think of these registered alarms as events that should be handled as soon as the system is idle.

Therefore, we will replace the call to time.sleep(5) with self.after(5000, callback). We use the self instance because the after() method is also available in the root Tk instance, and there will not be any difference in calling it from a child widget:

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=50, pady=20)

def start_action(self):
self.button.config(state=tk.DISABLED)
self.after(5000, lambda: self.button.config(state=tk.NORMAL))

if __name__ == "__main__":
app = App()
app.mainloop()

With the preceding approach, the application is responsive before the scheduled action is called. The appearance of the button will change to disabled, and we could also interact with the title bar as usual:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset