tkinter Button command doesn't work properly in iteration

Question:

I am making GUI and have some problems on the button command which is used to clear the input value .When i input a value into the 1st entry and try to click the 1st button , the value is not erased which should be cleared, Same as the 2nd button.But for the 3rd button ,it can clear the 3rd input value ,and the 1st,2nd button can also erase the value on 3rd entry.I want the 1st entry to 1st button and can erase data .What’s wrong with my code .How should i modify it .Your help is very gratefully appreciated.
Here is my code:

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()
Asked By: Raylene

||

Answers:

This is a tricky little corner of Python. Remember that your lambda function isn’t evaluated until the lambda is actually executed. By the time the lambda is executed, a has the value 2, for all three callbacks. What you need to do is "capture" the loop value, by passing it as a default parameter to the function:

    dict2[a]= Button(root,text='clear',command=lambda a=a :list1[a].set('')).place(relx=0.86,rely=0.32+label_rely)
Answered By: Tim Roberts
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.