Bind a widget from inside a class
Every example I've seen on this subject has shown a Button being bound to a command, except the Button widget was being made outside of a class:
e.g.:
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()
Now that's fine, except I get errors when attempting to do the following:
from Tkinter import *
class App():
def __init__(self,parent):
o = Button(root, text = 'Open', command = openFile)
开发者_JAVA技巧 o.pack()
def openFile(self):
print 'foo'
root = Tk()
app = App(root)
root.mainloop()
Replacing "command = openFile" with "command = self.openFile()" or "command = openFile()" also does not work.
How do I bind a function to a Button within my class?
command = self.openFile
If you type command = self.openFile()
you actually call the method and set the return value as the command. Accessing it without the brackets (like in the non-class version) gets you the actual method object. You need the self.
in the front, because otherwise Python attempts to look up openFile
from the global namespace.
The difference between App.openFile
and self.openFile
is that the latter is bound to the specific instance, whereas the first needs to be provided with an instance of App
when later calling it. The Python Data Model document contains more information about bound and unbound methods.
If event handler declaration is:
def handler(self):
It should be:
def handler(self,event):
This is because tk.bind()
insert the event
as implicit parameter to the handler. This happens no matters if event_handler
method is in a class or outside. Inside a class python adds on its own the self
object.
Sometimes, simplicity tends to obscure reality.
精彩评论