[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Later, we’ll see that class callback handler coding schemes provide a natural place to
remember information for use on events—simply assign the information to self
instance attributes:


class someGuiClass:
def __init__(self):
self.X = 42
self.Y = 'spam'
Button(text='Hi', command=self.handler)
def handler(self):
...use self.X, self.Y...

Because the event will be dispatched to this class’s method with a reference to the
original instance object, self gives access to attributes that retain original data. In effect,
the instance’s attributes retain state information to be used when events occur. Espe-
cially in larger GUIs, this is a much more flexible technique than global variables or
extra arguments added by lambdas.


Callable Class Object Callback Handlers


Because Python class instance objects can also be called if they inherit a call
method to intercept the operation, we can pass one of these to serve as a callback
handler too. Example 7-15 shows a class that provides the required function-like
interface.


Example 7-15. PP4E\Gui\Intro\gui3d.py


import sys
from tkinter import *


class HelloCallable:
def init(self): # init run on object creation
self.msg = 'Hello call world'


def call(self):
print(self.msg) # call run later when called
sys.exit() # class object looks like a function


widget = Button(None, text='Hello event world', command=HelloCallable())
widget.pack()
widget.mainloop()


Here, the HelloCallable instance registered with command can be called like a normal
function; Python invokes its call method to handle the call operation made in
tkinter on the button press. In effect, the general call method replaces a specific
bound method in this case. Notice how self.msg is used to retain information for use
on events here; self is the original instance when the special call method is au-
tomatically invoked.


All four gui3 variants create the same sort of GUI window (Figure 7-11), but print
different messages to stdout when their button is pressed:


392 | Chapter 7: Graphical User Interfaces

Free download pdf