How it works...

From the example mentioned in the preceding section, you might suppose the after() method executes the callback exactly after the given duration of milliseconds is passed as a delay.

However, what it does is request Tkinter to register an alarm that only guarantees that it will not be executed earlier than the specified time; so, if the main thread is busy, there is no upper limit to how long it will actually take.

We should also keep in mind that the method execution continues immediately after scheduling the action. The following example illustrates this behavior:

print("First")
self.after(1000, lambda: print("Third"))
print("Second")

The preceding snippet will print "First", then "Second", and finally "Third" after 1 second each. During this time, the main thread will keep the GUI responsive, and users can interact with the application as usual.

Usually, we would want to prevent the running of the same background action more than once, so it's a good idea to disable the widget that triggered the execution.

Do not forget that any scheduled function will be executed on the main thread, so just using after() is not enough to prevent freezing the GUI; it is also important to avoid executing long running methods as callbacks.

In the next recipe, we will take a look at how we can leverage the execution of these blocking actions in separate threads.

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

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