如何理解 lambda 中的闭包? [英] How to understand closure in a lambda?
问题描述
我想循环制作 5 个按钮,并为每个按钮绑定一个命令来打印索引.在以下解决方案中,它始终打印相同的索引.
I want to make 5 buttons in a loop, and for each buttons bind a commend to print the index. In the following solution it always prints the same index.
我的代码是这样的:
for i in range(5):
make_button = Tkinter.Button(frame, text ="make!",
command= lambda: makeId(i))
def makeId(i):
print(i)
它总是打印 5.我该如何解决这个问题?
It always prints 5. How can I fix this?
推荐答案
lambdas 中变量的解析是在执行 lambda 时完成的.此时,对于所有按钮 i=5.要纠正此问题,请执行以下操作:
Resolution of variables in lambdas is done when lambda is executed. At this time, for all buttons i=5. To rectify this issue do as follows:
make_button = Tkinter.Button(frame, text ="make!",
command= lambda i=i: makeId(i))
这将创建 i 作为 lambda 中的局部变量.这个局部变量将保存循环中正确的 i 值.局部变量可以有任何名称,不一定是 i
,例如command= lambda a=i: makeId(a))
.
This creates i as a local variable in a lambda. This local variable will hold correct value of i from the loop. the local variable can have any name, not necessarily i
, e.g. command= lambda a=i: makeId(a))
.
这篇关于如何理解 lambda 中的闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!