Binds not working on a specific part

只谈情不闲聊 提交于 2020-01-24 01:01:05

问题


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:


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.



来源:https://stackoverflow.com/questions/26941123/binds-not-working-on-a-specific-part

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!