在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
由于app是指向对象的指针,并且在循环中被覆盖,所以列表中的最后一个元素将是tk存储的值
这会复制对象,因此应用程序不会在循环中被覆盖
这样想吧。在您的循环中:
因此,您需要复制
app
的内容,以避免覆盖已有的值相关问题 更多 >
编程相关推荐