我试图用不同的参数调用相同的函数,对应于 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,以避免覆盖已经存在的值。
添加回答
举报
0/150
提交
取消