回调函数tkinter按钮具有可变参数 [英] Callback function tkinter button with variable parameter
问题描述
from tkinter import *
F=Tk()
i=1
while i<10:
newButton = Button(F,text="Show Number",command=lambda:showNumber(i))
newButton.pack(side=TOP)
i+=1
def showNumber(nb):
print(nb)
F.mainloop()
所有按钮返回10.为什么?
我要按钮1返回1,按钮2返回2 ...
¥b $ b非常感谢您帮助我。
All buttons return 10. Why ?
I want button 1 return 1, button 2 return 2...
Thank you very much for helping me
推荐答案
你的匿名 lambda
函数可以作为闭包(像@abernert指出的,实际上是在Python的情况下的闭包) - 他们关闭变量 i
,以后参考。但是,它们不会在定义时查找值,而是在调用时 之后的 整个 while
循环结束(此时 i
等于10)。
Your anonymous lambda
functions are can be though of as closures (as @abernert points out, they're not actually closures in Python's case) - they "close over" the variable i
, to reference it later. However, they don't look up the value at the time of definition, but rather at the time of calling, which is some time after the entire while
loop is over (at which point, i
is equal to 10).
要解决这个问题,您需要将 i
的值重新绑定到要使用的lambda的其他值。您可以通过多种方式完成此操作 - 这里有一个:
To fix this, you need to re-bind the value of i
to a something else for the lambda to use. You can do this in many ways - here's one:
...
i = 1
while i < 10:
# Give a parameter to the lambda, defaulting to i (function default
# arguments are bound at time of declaration)
newButton = Button(F, text="Show Number",
command=lambda num=i: showNumber(num))
...
这篇关于回调函数tkinter按钮具有可变参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!