Binds not working on a specific part

2019-06-12 22:54发布

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.

1条回答
三岁会撩人
2楼-- · 2019-06-12 23:38

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:

for x in range(0,len(columns)):
...
    l.bind("<Button-1>",lambda e, x=x: sortby(x))
#                                 ^^^

This is because the expression contained inside a lambda function is evaluated at call-time, not definition-time. So, the x in sortby(x) will always refer to the last value held by x in the loop.

Default arguments however are evaluated at definition-time. Thus, doing x=x ensures that x refers to the current value of x inside the loop.

查看更多
登录 后发表回答