explicitly request reloading of the modules that you change, but you must also generally
provide an indirection layer that routes callbacks from registered objects to modules
so that reloads have impact.
For example, the script in Example 10-14 goes the extra mile to indirectly dispatch
callbacks to functions in an explicitly reloaded module. The callback handlers regis-
tered with tkinter are method objects that do nothing but reload and dispatch again.
Because the true callback handler functions are fetched through a module object, re-
loading that module makes the latest versions of the functions accessible.
Example 10-14. PP4E\Gui\Tools\rad.py
reload callback handlers dynamically
from tkinter import *
import radactions # get initial callback handlers
from imp import reload # moved to a module in Python 3.X
class Hello(Frame):
def init(self, master=None):
Frame.init(self, master)
self.pack()
self.make_widgets()
def make_widgets(self):
Button(self, text='message1', command=self.message1).pack(side=LEFT)
Button(self, text='message2', command=self.message2).pack(side=RIGHT)
def message1(self):
reload(radactions) # need to reload actions module before calling
radactions.message1() # now new version triggered by pressing button
def message2(self):
reload(radactions) # changes to radactions.py picked up by reload
radactions.message2(self) # call the most recent version; pass self
def method1(self):
print('exposed method...') # called from radactions function
Hello().mainloop()
When run, this script makes a two-button window that triggers the message1 and
message2 methods. Example 10-15 contains the actual callback handler code. Its func-
tions receive a self argument that gives access back to the Hello class object, as though
these were real methods. You can change this file any number of times while the rad
script’s GUI is active; each time you do so, you’ll change the behavior of the GUI when
a button press occurs.
Example 10-15. PP4E\Gui\Tools\radactions.py
callback handlers: reloaded each time triggered
def message1(): # change me
Reloading Callback Handlers Dynamically | 629