[英]How to understand closure in a lambda?
I want to make 5 buttons in a loop, and for each buttons bind a commend to print the index.我想在一个循环中制作 5 个按钮,并为每个按钮绑定一个命令以打印索引。 In the following solution it always prints the same index.在以下解决方案中,它始终打印相同的索引。
My code like this:我的代码是这样的:
for i in range(5):
make_button = Tkinter.Button(frame, text ="make!",
command= lambda: makeId(i))
def makeId(i):
print(i)
It always prints 5. How can I fix this?它总是打印 5。我该如何解决这个问题?
Resolution of variables in lambdas is done when lambda is executed. lambda 中的变量解析是在执行 lambda 时完成的。 At this time, for all buttons i=5.此时,对于所有按钮,i=5。 To rectify this issue do as follows:要纠正此问题,请执行以下操作:
make_button = Tkinter.Button(frame, text ="make!",
command= lambda i=i: makeId(i))
This creates i as a local variable in a lambda.这会将 i 创建为 lambda 中的局部变量。 This local variable will hold correct value of i from the loop.此局部变量将保存循环中 i 的正确值。 the local variable can have any name, not necessarily i
, eg command= lambda a=i: makeId(a))
.局部变量可以有任何名称,不一定是i
,例如command= lambda a=i: makeId(a))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.