为了账号安全,请及时绑定邮箱和手机立即绑定

在 Tkinter 中使用 for in 和函数调用时,函数参数值仅显示列表中的最后一个元素?

在 Tkinter 中使用 for in 和函数调用时,函数参数值仅显示列表中的最后一个元素?

白衣染霜花 2023-04-18 15:12:28
我试图用不同的参数调用相同的函数,对应于 Tkinter python 中的 for in 和按钮,当我单击其他按钮时,函数给出的值是最后调用的值。我是一名 js 开发人员,曾将 foreach 和 array 与类似的东西一起使用。apps=["k","c","d"] for app in apps:        btn = tk.Button(innerFrame, text=" {}".format(app), command=(            lambda: runThis(app)))        btn.pack()       def runThis(val, i):    print("Value of the btn {}".format(val))单击每个按钮时的预期输出是Value of the btn kValue of the btn cValue of the btn d但我得到的是Value of the btn dValue of the btn dValue of the btn d
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

由于 app 是指向对象的指针,并且它在循环中被覆盖,列表中的最后一个元素将是 tk 存储的值。


btn = tk.Button(innerFrame, text=name, command=lambda app=app: runThis(app))

这会复制对象,因此应用程序不会在您的循环中被覆盖。


这样想。在你的循环中:


#first loop

app = "k"

function(points to -> app -> points to "k") #first


#second loop

app = "c"

function(points to -> app -> points to "c") #first

function(points to -> app -> points to "c") #second


#third loop

app = "d"

function(points to -> app -> points to "d") #first

function(points to -> app -> points to "d") #second

function(points to -> app -> points to "d") #third

因此,您需要复制 的内容app,以避免覆盖已经存在的值。


查看完整回答
反对 回复 2023-04-18
  • 1 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信