'Get the value of an entry created with a button
I am new to python tkinter.I would like to get some help from you.
After adding a few entries with the button (Add_button), then entering a value to each of them, I would like to know how I can get the value from those entries and add them up.
I tried a few things, they did not work.
from tkinter import *
root=Tk()
s=0
def add_button():
global s
s +=1
for i in range(s):
lab1=Label(root, text='lab1')
lab1.grid(row=i, column=1)
entry1=Entry(root)
entry1.grid(row=i, column=2)
bouton_add=Button(root, text='Create widget', command=add_button )
bouton_add.grid(row=5, column=0)
root.mainloop()
Solution 1:[1]
from tkinter import *
root=Tk()
a=[]
s=0
def add_button():
global s
s +=1
lab1=Label(root, text=f'lab{s}')
lab1.grid(row=s, column=0)
entry1=Entry(root)
a.append(entry1)
entry1.grid(row=s, column=1)
def get_entry():
a_data=[]
for i in a:
a_data.append(i.get())
print(a_data)
bouton_add=Button(root, text='Create widget', command=add_button )
bouton_add.grid(row=5, column=0)
bouton_add=Button(root, text='get', command=get_entry )
bouton_add.grid(row=5, column=1)
root.mainloop()
The for-loop with range(s) would create a new entry over the previous entry, so even if you use the get_entry method, you will get result on previous entry as '' only.
I have just stored references to the entry when they are create in a list, and to get their value, used a for loop for elements in the list a, and used .get method to get thier value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Faraaz Kurawle |
