user2067309
user2067309

Reputation: 1

getting the contents of each entry in a loop

I'm using tkinter with Python to get a query from the user and print the contents of each entry in a loop. However, only the text of the the last entry gets printed. What should I do to fix the problem?

for i in range(len(labels)):
    label=Label(V,text=i, relief=RIDGE,width=8)
    label.pack()
    label.grid(row=counter,column=1,padx=5,pady=5)
    entry = Entry(V, relief=SUNKEN,width=30,justify=RIGHT)
    entry.pack()
    entry.grid(row=counter,column=0,padx=10,pady=5)
    def showevent (event):
        print entry.get()

    entry.bind("<Return>", showevent)

Upvotes: 0

Views: 105

Answers (1)

mgilson
mgilson

Reputation: 309959

This is a common misconception with closures. Basically, entry is looked up when the function is run, not defined. The simple fix is to make it a default argument:

def showevent(event,entry=entry):
    print entry.get()

This works because default arguments are evaluated at the time the function is created, not when it is called so you always get the entry that you want.

Upvotes: 3

Related Questions