Reputation: 14257
I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:
for method in methods:
button = Button(self.methodFrame, text=method, command=self.populateMethod)
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
That part works fine. However, I need to know which of the buttons was pressed inside self.populateMethod
. Any advice on how I might be able to tell?
Upvotes: 10
Views: 16332
Reputation: 385800
You can use lambda to pass arguments to a command:
def populateMethod(self, method):
print "method:", method
for method in ["one","two","three"]:
button = Button(self.methodFrame, text=method,
command=lambda m=method: self.populateMethod(m))
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
Upvotes: 24
Reputation: 2576
It seems that the command method is not passed any event object.
I can think of two workarounds:
associate a unique callback to each button
call button.bind('<Button-1>', self.populateMethod)
instead of passing self.populateMethod as command
. self.populateMethod must then accept a second argument which will be an event object.
Assuming that this second argument is called event
, event.widget
is a reference to the button that was clicked.
Upvotes: 2