Reloading Callback Handlers Dynamically
Our next GUI-programming technique is all about changing
a GUI while it is running—the ultimate in customization. The Python
reload
function lets you
dynamically change and reload a program’s modules without stopping the
program. For instance, you can bring up a text editor window to change
the source code of selected parts of a system while it is running and
see those changes show up immediately after reloading the changed
module.
This is a powerful feature, especially for developing programs
that take a long time to restart. Programs that connect to databases
or network servers, initialize large objects, or travel through a long
series of steps to retrigger a callback are prime candidates for
reload
. It can shave substantial
time from the development cycle.
The catch for GUIs, though, is that because callback handlers
are registered as object references rather than
module and object names, reloads of callback handler functions are
ineffective after the callback has been registered. The Python
reload
operation works by changing
a module object’s contents in place. Because Tkinter stores a pointer
to the registered handler object directly, though, it is oblivious to
any reloads of the module that the handler came from. That is, Tkinter
will still reference a module’s old objects even after the module is
reloaded and changed.
This is a subtle thing, but you really only need to remember that you must do something special to reload callback ...
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.