0

I'm trying to create a sign-up form using Python and Tkinter...

To keep things tidy, I would like to iterate over the elements of this list:

signup_fields = ['first_name', 'last_name', 'username', 'password', 'confirm_password', 'email', 'confirm_email', 'height', 'weight']

With something like this for loop being used to create the entry boxes:

for field in signup_fields:
    {field} = tk.Entry()
    {field}.pack()

As you can see, I'm putting 'field' in '{}' curly brackets to try get Python to name the variables based on the strings from the list. I don't know how to do this and I'm not finding a workaround online.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • I just want to emphasize what Bryan said in his answer: **you don't want to do that**. It is possible through trickery to create variable-named variables, but it's always a bad idea. It's not the right way to do things. Use a list or a dict. – Tim Roberts Aug 12 '21 at 22:38
  • It is technically possible to do this with exec or globals/locals but I will third the advice to use a dict. Every other way is worse. Use a dict. – CJR Aug 12 '21 at 22:43
  • @CJR technically, it is *not* possible in local scopes, only global scopes – juanpa.arrivillaga Aug 12 '21 at 23:22
  • Do *not* do this. Use a *container*, like a list or a dict. – juanpa.arrivillaga Aug 12 '21 at 23:22

1 Answers1

3

You don't want to do that. Instead, store the widgets in a dictionary. The code will be much easier to understand and debug.

entries = {}
for field in signup_fields:
    entries[field] = tk.Entry()

For other alternatives, see How do I create variable variables?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685