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

我试图用不同的参数调用相同的函数,对应于 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 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


白衣染霜花
浏览 66回答 1
1回答

慕莱坞森

由于 app 是指向对象的指针,并且它在循环中被覆盖,列表中的最后一个元素将是 tk 存储的值。btn = tk.Button(innerFrame, text=name, command=lambda app=app: runThis(app))这会复制对象,因此应用程序不会在您的循环中被覆盖。这样想。在你的循环中:#first loopapp = "k"function(points to -> app -> points to "k") #first#second loopapp = "c"function(points to -> app -> points to "c") #firstfunction(points to -> app -> points to "c") #second#third loopapp = "d"function(points to -> app -> points to "d") #firstfunction(points to -> app -> points to "d") #secondfunction(points to -> app -> points to "d") #third因此,您需要复制 的内容app,以避免覆盖已经存在的值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python