So earlier in my program, I use the line
l.bind("<Button-1>",lambda e: getSide(i))
and when I click on the element, it works fine.
However, later I use the line
l.bind("<Button-1>",lambda e: sortby(x))
for a different local object.
getSide
is a stub that prints the value of i
defined when binding. sortby
is a Quicksort that (for debugging purposes) prints the value of x
at the start. The curious thing is that while getSide
returns the correct value, sortby
does not.
getSide
returns i
, whereas sortby
prints len(column)-1
, i.e the last Label to be bound.
The problem is that you are creating these bindings inside a loop. When you do this, you must "capture" any values you use inside a lambda function in its argument list:
This is because the expression contained inside a lambda function is evaluated at call-time, not definition-time. So, the
x
insortby(x)
will always refer to the last value held byx
in the loop.Default arguments however are evaluated at definition-time. Thus, doing
x=x
ensures thatx
refers to the current value ofx
inside the loop.