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.
functioncan be any callable Python object: a function, bound method, etc. This form of the call does not pause the program -- the callback function is run later from the normal Tkinter event loop. The milliseconds value can be a floating point number, to specify fractions of a second. This returns an ID which can be passed toafter_cancelto 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 5000 pauses for 5 seconds. This is essentially the same as Python’s library function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access