让我们回到GUI编程,尽管函数和lambda表达式在许多情况下已经够用,类实例的bound方法在GUI程序中作为回调处理器特别好用,它们既可以记录事件发送的目标实例也可以记录相关方法调用的实例。例如:
from tkinter import *
class HelloClass:
def __init__(self):
widge = Button(None, text='hello event world', command=self.quit)
widge.pack()
def quit(self):
print('hello event world')
sys.exit()
HelloClass()
mainloop()
这段代码采用了注册bound类方法而不是函数或lambda,按钮按下时,tkinter像通常一样无参调用该类的quit方法。在实际上,它去收到了一个参数——原始的self对象,尽管tkinter没有显式地传递它。因为self.quit的bound方法包括了self和quit,可与简单的函数调用共用,python会自动将self参数传递给method函数。相反的,注册带一个参数的UNbound实例方法,如HelloClass.quit,并不起作用,因为稍后事件发生时,没有self对象来传值。
后来,我们会看到类回调处理器的编码方案提供了一个天然的位置来记录用于事件的信息,只需将信息添加到self实例的属性中:
from tkinter import *
class HelloClass:
def __init__(self):
self.x = 3
self.y = 4
widge = Button(None, text='hello event world', command=self.quit)
widge.pack()
def handler(self):
调用self.x和self.y