How can I get the tkinter entry from a loop

Luuk Verhagen picture Luuk Verhagen · Feb 19, 2015 · Viewed 7.7k times · Source

I wants to make a program with multiple tkinter Entry widgets. I use a for loop to make multiple Entry widgets. But how can I get the value from it?

My test code:

from tkinter import *

root=Tk()
variables = []
entries = []
for i in range(10):
    va = StringVar()
    en = Entry(root, textvariable=va)
    en.grid(row=i+1, column=0)
    variables.append(va)
    entries.append(en)

def hallo():
    print(en.get())
button=Button(root,text="krijg",command=hallo).grid(row=12,column=0)

root.mainloop()

Answer

fhdrsdg picture fhdrsdg · Feb 19, 2015

If you use StringVars, you need to use get() on those. However, there seems to be no need for you to use StringVars, so you can just remove those and use get() on the entry widgets like so:

from tkinter import *

root=Tk()
entries = []

for i in range(10):
    en = Entry(root)
    en.grid(row=i+1, column=0)
    entries.append(en)

def hallo():
    for entry in entries:
        print(entry.get())

button=Button(root,text="krijg",command=hallo).grid(row=12,column=0)

root.mainloop()