从类内部绑定小部件

Gar*_*t H 0 python tkinter

我在这个主题上看到的每个例子都显示一个Button被绑定到一个命令,除了Button小部件是在一个类之外创建的:

例如:

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()
Run Code Online (Sandbox Code Playgroud)

现在没问题,除了我在尝试执行以下操作时遇到错误:

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()
Run Code Online (Sandbox Code Playgroud)

用"command = self.openFile()"或"command = openFile()"替换"command = openFile"也不起作用.

如何将函数绑定到我的类中的Button?

sha*_*ang 5

command = self.openFile

如果键入command = self.openFile(),则实际调用该方法并将返回值设置为命令.在没有括号的情况下访问它(就像在非类版本中一样)可以获得实际的方法对象.你需要self.在前面,因为否则Python会尝试openFile从全局命名空间中查找.

App.openFile和之间的区别在于self.openFile后者绑定到特定实例,而第一个需要提供一个App后来调用它的实例.在Python的数据模型文件包含有关绑定和非绑定方法的详细信息.