绑定不适用于特定零件 [英] Binds not working on a specific part
问题描述
因此,在程序的前面,我使用了该行
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))
用于其他本地对象.
getSide
是一个存根,它显示绑定时定义的i
的值. sortby
是一个Quicksort(出于调试目的)在开始时打印x
的值.奇怪的是,尽管getSide
返回正确的值,但sortby
却没有.
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
返回i
,而sortby
打印len(column)-1
,即要绑定的最后一个Label.
getSide
returns i
, whereas sortby
prints len(column)-1
, i.e the last Label to be bound.
推荐答案
问题是您正在循环内创建这些绑定.执行此操作时,必须捕获"在lambda函数的参数列表中使用的所有值:
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))
# ^^^
这是因为lambda函数中包含的表达式是在调用时而不是定义时求值的.因此,sortby(x)
中的x
将始终引用循环中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.
但是,默认参数是在定义时求值的.因此,执行x=x
可以确保x
引用循环内x
的当前值.
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.
这篇关于绑定不适用于特定零件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!