Time Tools, Threads, and Animation
The last stop on our widget tour is the most unique. Tkinter also comes with a handful of tools that have to do with the event-driven programming model, not graphics displayed on a computer screen.
Some GUI applications need to perform background activities periodically. For example, to “blink” a widget’s appearance, we’d like to register a callback handler to be invoked at regular time intervals. Similarly, it’s not a good idea to let a long-running file operation block other activity in a GUI; if the event loop could be forced to update periodically, the GUI could remain responsive. Tkinter comes with tools for both scheduling such delayed actions and forcing screen updates:
widget.after(
milliseconds, function, *args
)
This tool schedules the function to be called after a number of milliseconds.
function
can be any callable Python object: a function, bound method, and so on. This form of the call does not pause the program—the callback function is run later from the normal Tkinter event loop. Themilliseconds
value can be a floating-point number, to specify fractions of a second. This returns an ID that can be passed toafter_cancel
to cancel the callback. Since this method is so commonly used, I’ll say more about it by example in a moment.widget.after(
milliseconds
)
This tool pauses the program for a number of milliseconds—for example, an argument of 5,000 pauses for 5 seconds. This is essentially the same as Python’s library function,
time.sleep ...
Get Programming Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.