【问题标题】:tkinter Button command doesn't work properly in iteration [duplicate]tkinter 按钮命令在迭代中无法正常工作 [重复]
【发布时间】:2021-04-26 01:56:49
【问题描述】:

我正在制作 GUI,但用于清除输入值的按钮命令有一些问题。当我在第一个条目中输入一个值并尝试单击第一个按钮时,该值不会被清除,应该清除,和第2个按钮一样。但是对于第3个按钮,它可以清除第3个输入值,第1、2个按钮也可以清除第3个输入的值。我想要第1个输入到第1个按钮,并且可以清除数据。什么我的代码有问题。我应该如何修改它。非常感谢您的帮助。 这是我的代码:

from tkinter import *
root = Tk()
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
root.title('PN List Box')
root.geometry("500x300+%d+%d"%((screenwidth-400)/2,(screenheight-230)/2-100))
mycolor = '#%02x%02x%02x' % (101, 119, 141)
root.configure(bg=mycolor)
cv = Canvas(root,bg=mycolor)
dict1={}
dict2={}
list1=[]
label_rely=0
for a in range(3):
    label_rely+=0.1
    list1.append(StringVar())
    dict1[a]=Entry(root,textvariable=list1[a]).place(relx=0.27, rely=0.33 + label_rely)
    dict2[a]= Button(root,text='clear',command=lambda :list1[a].set('')).place(relx=0.86,rely=0.32+label_rely)

root.mainloop()

sys.exit()

【问题讨论】:

    标签: python tkinter button


    【解决方案1】:

    这是 Python 的一个棘手的小角落。请记住,在实际执行 lambda 之前,不会评估您的 lambda 函数。到执行 lambda 时,a 对于所有三个回调都具有值 2。您需要做的是“捕获”循环值,将其作为默认参数传递给函数:

        dict2[a]= Button(root,text='clear',command=lambda a=a :list1[a].set('')).place(relx=0.86,rely=0.32+label_rely)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多