How it works...

To create a new Thread object, we can use the constructor with the target keyword argument, which will be invoked on a separate thread when we call its start() method.

In the preceding section, we used a reference to the run_action method on the current application instance:

    thread = threading.Thread(target=self.run_action)
thread.start()

Then, we periodically polled the thread status using after(), which schedules the same method again until the thread is finished:

    def check_thread(self, thread):
if thread.is_alive():
self.after(100, lambda: self.check_thread(thread))
else:
self.button.config(state=tk.NORMAL)

In the preceding code snippet, we set a delay of 100 milliseconds, because there is no need to keep polling more frequently than that. Of course, this number may vary depending on the nature of the threaded action.

This timeline can be represented by the following sequence diagram:

The rectangle on Thread-1 represents the time it is busy executing time.sleep(5). Meanwhile, MainThread only checks the status periodically, and there is no operation long enough to causes it to freeze the GUI.

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

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