1

I need to create a large number of variables that take string input and that initially will be empty (pending user input).

Previously I've created the variables one at the time, eg

customer_id = StringVar() customer_age = StringVar()

etc but this looks messy with a large number of variables.

I've looked at the answer in Issue with 'StringVar' in Python Program but I can't figure out how to use StringVar() with a for loop and a list.

I'm using Python 3.7.4, Windows 10.

# ATTEMPT 
from tkinter import * 
varlist = ['customer_id', 'customer_age', 'customer_phone']               
for var in varlist:
    Tk()
    var = StringVar()

# ERROR MESSAGE WHEN CHECKING VARIABLES
type(customer_id) 

NameError                                 Traceback (most recent call last)
<ipython-input-24-9625f8af3cc2> in <module>
----> 1 type(customer_id)

NameError: name 'customer_id' is not defined

Thanks!

1
  • Part of the problem is that you're creating multiple root windows. You need to remove Tk() from the loop. Commented Nov 23, 2019 at 15:17

1 Answer 1

2

Use a dict.

varlist = {var: StringVar() for var in ["customer_id", "customer_age", "customer_phone"]}

Now use varlist["customer_id"] where you would have used the variable customer_id.

Sign up to request clarification or add additional context in comments.

2 Comments

When I run it I get: File "<ipython-input-6-35d53a43f178>", line 7 varlist = {var: StringVar() for var in "customer_id", "customer_age", "customer_phone"} ^ SyntaxError: invalid syntax
Fixed; I forgot to wrap the elements in a list literal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.