Tkinter 使用 lambda 循环分配按钮命令 [英] Tkinter assign button command in loop with lambda

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

问题描述

我正在尝试像这样创建一些 Button(带有 for 循环):

I'm trying to create a few Buttons (with a for loop) 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

并且每个按钮都有自己的参数(测试得到 Test" 和 Test2 得到 Test2"),但是当我按下按钮时都打印 "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.

我该如何解决这个问题?

How can I solve this?

推荐答案

问题在于 for 循环中的 Lamba.您的 lambda 正在使用 name 变量,但每次通过 for 循环都会重新分配 name 变量.所以最后,所有按钮都获得了 name 在 for 循环中分配给的最后一个值.为避免这种情况,您可以在 Lamba 表达式中使用默认关键字参数,如下所示:

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))

每次循环时,这都会将 name 变量的当前值绑定到 Lamba 的 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 使用 lambda 循环分配按钮命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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