0

I have a function, say foo and it's supposed to bind an event

    def foo:
         for x in widget_list:
              widget.config(command = lambda: self.function(widget_list.index(x))

    def function(index):
         do something here....
         print index

The widget list contains buttons, and whenever I click corresponding buttons, they're supposed to print to the IDLE their index, but what happens is that all the buttons I click end up printing the last index of widget_list. I'm guessing that while for iterates, the argument of the function also changes thus only the last index is preserved. Is there anyway to bind the previous indexes to the button?

  • You guess right that only the last value of x is used in your lambdas. You might find work around in this answer: http://stackoverflow.com/a/2295368 – FabienAndre Mar 24 '14 at 13:01
  • Finally. I have been searching for such a solution here for about a week now but I guess I have miscategorized this a a tkinter only problem. Anyways, thank you as I can progress with my work now. :D – user3455382 Mar 24 '14 at 13:14
  • possible duplicate of [Passing argument to a function via a Button in Tkinter, starnge behaviour in loop](http://stackoverflow.com/questions/18510403/passing-argument-to-a-function-via-a-button-in-tkinter-starnge-behaviour-in-loo) – FabienAndre Mar 24 '14 at 13:18

1 Answers1

0

The simplest fix is to make sure that your lambda is using the current value of x:

widget.config(command = lambda x=x: self.function(widget_list.index(x))

This forces x to be a default parameter to the function, and the default value will be the value of x at the time the lambda is defined.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685