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. The milliseconds value can be a floating-point number, to specify fractions of a second. This returns an ID that can be passed to after_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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.