tags:

views:

61

answers:

2

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?

+1  A: 

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.

RaphaelSP
I did the second method and it seems to do what I want. Thanks!
Sydius
+2  A: 

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})
Bryan Oakley
Ooh, clever. Thanks.
Sydius