Tkinter的与拉姆达循环分配的按钮命令 [英] Tkinter assign button command in loop with lambda

查看:248
本文介绍了Tkinter的与拉姆达循环分配的按钮命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建几个按钮(用的),像这样:

I'm trying to create a few buttons (with a for) like so:

def a(self, name):
    print name

users = {"Test":"127.0.0.0", "Test2":"128.0.0.0"}
row = 1
for name in users:
    user_button = Tkinter.Button(self.root,
                                 text=name,
                                 command=lambda: self.a(name))
    user_button.grid(row = row, column = 0)
    row+=1

以及按钮到每个获得自己的参数(测试得到测试和TEST2得到的Test2),但是当我preSS按钮他们都打印Test2的,这意味着它们使用相同的函数具有相同参数。

and for the buttons to each get their own parameter (Test getting Test and Test2 getting Test2) but when i press the buttons they both print "Test2" which means they are using the same function with the same parameter.

我该如何解决呢?

推荐答案

问题是您在兰巴for循环。您拉姆达使用名称变量,但名称变量被每一次重新分配,通过for循环。所以,最后,所有的按键得到名字的最后一个值被分配到for循环。为了避免这种情况,你可以使用默认的关键字参数在兰巴前pression像这样:

The problem is your lamba in the for loop. Your lambda is using the name variable, but the name variable gets reassigned each time through the for loop. So in the end, all of the buttons get the last value that name was assigned to in the for loop. To avoid this you can use default keyword parameters in your lamba expression like so:

user_button = Tkinter.Button(self.root,
                             text=name,
                             command=lambda name=name: self.a(name))

本绑定名称的当前值变量的兰巴的名称关键字参数通过每次循环,产生期望的效果。

This binds the current value of the name variable to the lamba's name keyword argument each time through the loop, producing the desired effect.

这篇关于Tkinter的与拉姆达循环分配的按钮命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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