Checkbuttons And Buttons: Using Lambda
I am trying to make a number of checkboxes based on a list, however it looks as if I am screwing up the command call and variable aspect of the button. My code is: class Example(
Solution 1:
When you make a lambda
function, its references only resolve into values when the function is called. So, if you create lambda
functions in a loop with a mutating value (i
in your code), each function gets the same i
- the last one that was available.
However, when you define a function with a default parameter, that reference is resolved as soon as the function is defined. By adding such a parameter to your lambda
functions, you can ensure that they get the value you intended them to.
lambda i=i: self.onClick(i)
This is referred to as lexical scoping or closure, if you'd like to do more research.
Post a Comment for "Checkbuttons And Buttons: Using Lambda"