Tkinter.使用“不同"按钮创建多个按钮.命令功能 [英] Tkinter. Create multiple buttons with "different" command function

查看:724
本文介绍了Tkinter.使用“不同"按钮创建多个按钮.命令功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不起标题,我找不到更好的标题.

first of all, sorry for the title, I couldn't find a better one.

以下代码是我在Python程序中遇到的问题的简化版本(我是新手).

The following code is a minimalized version of a problem I have in my Python program (I am a newbie btw.).

def onClick(i):
    print "This is Button: " + str(i)
    return

def start():
    b = [0 for x in range(5)]
    win = Tkinter.Tk()
    for i in range(5):
        b[i] = Tkinter.Button(win,height=10,width=100,command=lambda : onClick(i))
        b[i].pack()
    return

它的作用: 无论我单击哪个按钮,它都会显示这是按钮:4".

What it does: Whatever Button I click, it says "This is Button: 4".

我想要什么: 第一个按钮应显示"This is Button:0",依此类推.

What I want: First button should say "This is Button: 0" and so on.

这是Python的通缉行为吗?如果答案是肯定的,那为什么会这样呢?我该如何解决?

Is this a wanted behaviour of Python? And if the answer is yes, why is that so? How can I fix it?

另一方面,这很好:

def start():        
    x = [0 for x in range(5)]
    for i in range(5):
        x[i] = lambda:onClick(i)
        x[i]()
    return

推荐答案

使用默认参数避免出现后期绑定问题(否则,在调用lambda函数时(而不是在创建函数时)绑定i):

Use default parameter to avoid late-binding issue (Otherwise i is bound when the lambda function is called, not when it is created):

def start():
    buttons = []
    win = Tkinter.Tk()
    for i in range(5):
        b = Tkinter.Button(win, height=10, width=100, command=lambda i=i: onClick(i))
        b.pack()
        buttons.append(b)

这篇关于Tkinter.使用“不同"按钮创建多个按钮.命令功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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