2011-02-05 58 views
0

我已经看到在这个问题上的每个实例显示一个按钮被绑定到的命令的类的内部绑定的微件,除了按钮构件是被一类的外部进行:

例如:

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() 

更换 “命令=中openFile” 与 “命令= self.openFile()” 或 “命令=中openFile()”也不禾RK。

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

回答

5

command = self.openFile

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

App.openFileself.openFile之间的区别在于后者与特定实例绑定,而第一个需要在稍后调用它时提供App的实例。 Python Data Model document包含有关绑定和未绑定方法的更多信息。