在类内部绑定小部件
我看到的每个例子都是把一个按钮和一个命令绑定在一起,不过这些按钮都是在类外面创建的:
比如:
from Tkinter import *
root = Tk()
def callback(event):
print "clicked at", event.x, event.y
frame = Frame(root, width=100, height=100)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
这没问题,但当我尝试这样做的时候却出现了错误:
from Tkinter import *
class App():
def __init__(self,parent):
o = Button(root, text = 'Open', command = openFile)
o.pack()
def openFile(self):
print 'foo'
root = Tk()
app = App(root)
root.mainloop()
把“command = openFile”替换成“command = self.openFile()”或者“command = openFile()”也不行。
我该怎么在我的类里面把一个函数绑定到按钮上呢?
2 个回答
1
如果事件处理程序的声明是:
def handler(self):
那么它应该是:
def handler(self,event):
这是因为 tk.bind()
会自动把 event
作为隐含参数传递给处理程序。无论 event_handler
方法是在类里面还是外面,这种情况都是一样的。在类里面,Python 会自动添加 self
对象。
有时候,简单的东西反而会让事情变得不清楚。
5
command = self.openFile
如果你输入 command = self.openFile()
,其实是调用了这个方法,并把它返回的结果赋值给了命令。没有括号的情况下访问它(就像在非类的版本中那样),你得到的就是这个方法本身。前面需要加 self.
,因为如果不加,Python会试图从全局范围内查找 openFile
。
App.openFile
和 self.openFile
的区别在于,后者是绑定到特定的实例上的,而前者在后面调用的时候需要提供一个 App
的实例。有关绑定和未绑定方法的更多信息,可以查看 Python 数据模型文档。