带可变参数的回调函数tkinter按钮 [英] Callback function tkinter button with variable parameter

查看:47
本文介绍了带可变参数的回调函数tkinter按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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...
非常感谢你帮助我

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<之后的某个时间/code> 循环结束(此时 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆