Reputation: 11
I'm trying to create multiple entry boxes with a for loop, so i don't have to make all the different boxes manually in case i want to increase the amount of entries, but this way I can't get my entry value via .get(). If i print L1 the output is a list of three empty strings, so no value was added after I typed them into the entry boxes. How can I make a list containing all the entry values as floats?
from tkinter import *
window = Tk()
window.geometry("450x450+200+200")
def do():
print(L1)
L1 = []
for i in range(3):
labelx = Label(window, text = str(i)).grid(row = i, column = 0)
v = StringVar()
num = Entry(window, textvariable = v).grid(row = i, column = 1)
num1 = v.get()
L1.append(num1)
button1 = Button(window, text = 'OK', command = do).grid(column = 1)
Upvotes: 1
Views: 617
Reputation: 385900
Your original code is storing the value in a list. Instead, store a reference to the widget. With this, there's no reason to create the StringVar
objects.
Note that to do this you must create the widget and call grid
as two separate statements. It not only allows this technique to work, it's generally considered a best practice to separate widget creation from widget layout.
L1 = []
for i in range(3):
labelx = Label(window, text = str(i))
num = Entry(window, textvariable = v)
labelx.grid(row = i, column = 0)
num.grid(row = i, column = 1)
L1.append(num)
...
for widget in L1:
print("the value is", widget.get())
Upvotes: 1
Reputation:
Use the list, L1, to store the id of the Tkinter StringVar(). Use the get method in the function called by the button. Otherwise, how is the program to know when the data is ready to be retrieved. A StringVar returns a string that will have to be converted to a float. Also, it's a bad habit to use i, l, or o as single digit variable names as they can look like numbers.
window = Tk()
window.geometry("450x450+200+200")
def do():
for var_id in L1:
print(var_id.get())
var_id.set("")
L1 = []
for ctr in range(3):
## grid() returns None
Label(window, text = str(ctr)).grid(row = ctr, column = 0)
var_id = StringVar()
ent=Entry(window, textvariable = var_id)
ent.grid(row = ctr, column = 1)
##num1 = v.get()-->nothing entered when program starts
if 0==ctr:
ent.focus_set()
L1.append(var_id)
button1 = Button(window, text = 'OK', command = do).grid(column = 1)
window.mainloop()
Upvotes: 0