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

2024-04-26 12:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在Tkinter python中,我试图用不同的参数调用同一个函数,对应于for in和buttons,当我单击其他按钮时,该函数给出的值就是最后一次调用的值。我是一个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 k
Value of the btn c
Value of the btn d

但我得到的是

Value of the btn d
Value of the btn d
Value of the btn d

1条回答
网友
1楼 · 发布于 2024-04-26 12:02:38

由于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的内容,以避免覆盖已有的值

相关问题 更多 >