Title: Bind a widget from inside a class
Tags: python;tkinter
Question: 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:
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&gt;", 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)
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?

Here is the accepted answer: 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.

Here is another answer: 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.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 2.5', 'CreationDate': '2011:00:02/05/11', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<python><tkinter>', 'Title': 'Bind a widget from inside a class', 'ViewCount': 1557, 'id': 4908426, 'user_AboutMe': 'iPhone developer for BlueDoorway, inc.', 'user_AccountId': 88359.0, 'user_DisplayName': 'Garrett H', 'user_Reputation': 148.0, 'user_Views': 7.0, 'user_id': 244440.0}}