Accessing Dynamically Created Tkinter Widgets
I am trying to make a GUI where the quantity of tkinter entries is decided by the user. My Code: from tkinter import* root = Tk() def createEntries(quantity): for num in rang
Solution 1:
The solution is to store the widgets in a data structure such as a list or dictionary. For example:
entries = []
for num in range(quantity):
usrInput = Entry(root, text = num)
usrInput.pack()
entries.append(usrInput)
Later, you can iterate over this list to get the values:
for entry in entries:
value = entry.get()
print("value: {}".format(value))
And, of course, you can access specific entries by number:
print("first item: {}".format(entries[0].get()))
Solution 2:
With the following Code you can adjust the number of Buttons and Entrys depending on the Var "fields". I hope it helps
from tkinter import *
fields ='Last Name', 'First Name', 'Job', 'Country'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"'% (field, text))
def makeform(root, fields):
entries = []
for field in fields:
row= Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
if __name__ =='__main__':
root = Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: fetch(e)))
b1 = Button(root, text='Show',
command=(lambda e=ents: fetch(e)))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='Quit', command=root.quit)
b2.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
Post a Comment for "Accessing Dynamically Created Tkinter Widgets"