-1

When we have to create tk objects with loops it's a relief. But what about times that we want to name them as var0=first_entry then var1=second_entry etc...? What is the most elegant way to do it?

While i < 10:
            self.p{i} = tk.Entry(tk.Frame,
                        width=12).grid(row=2, column=i, pady=10) 
                        # self.p{i} is where i'm stuck
martineau
  • 119,623
  • 25
  • 170
  • 301
Ash
  • 263
  • 3
  • 14
  • 1
    Note to close voters: This question is about creating `tkinter.Entry` widgets, not variables in general. – martineau Sep 27 '19 at 22:02

1 Answers1

1

What you basically want, is nothing else than a dictionary (replace the assigned i with your Tkinter expression):

d = {}
for i in range(10):
    d["var{0}".format(i)] = i

Output:

d
{'var0': 0,
 'var1': 1,
 'var2': 2,
 'var3': 3,
 'var4': 4,
 'var5': 5,
 'var6': 6,
 'var7': 7,
 'var8': 8,
 'var9': 9}
Julia K
  • 397
  • 3
  • 10
  • Thank you. But how can I access that later? When I want to call it using `keys/items` for binding it to a method e.g. `self.var0.bind(blah blag)` it returns `'_tkinter.tkapp' object has no attribute 'self.var0'`. – Ash Sep 27 '19 at 21:10
  • you access it, for example with `d['var0']`. If the dictionary is an instance variable of a class, you access it via `instanceOfClass.d['var0']`. – Julia K Sep 27 '19 at 21:21