H K V
H K V

Reputation: 3

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 range(quantity):
        usrInput = Entry(root, text = num)
        usrInput.pack()

createEntries(10)

root.mainloop()

This code is based on this tutorial i found:

for num in range(10):
    btn = tkinter.button(window, text=num)
    btn.pack(side=tkinter.LEFT)

The problem is that I can only access the input in the latest created widget, because they all have the same name. Is there a way of dynamically creating widgets with unique names?

Any advice would be greatly appreciated

Upvotes: 0

Views: 1028

Answers (2)

Holger
Holger

Reputation: 74

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()

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386342

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()))

Upvotes: 1

Related Questions