从Tkinter使用StringVar()创建多个空字符串变量

时间:2019-11-23 13:13:54

标签: python tkinter

我需要创建大量使用字符串输入的变量,这些变量最初将为(待输入用户)。

以前,我一次创建了一个变量,例如

customer_id = StringVar() customer_age = StringVar()

等,但是带有大量变量看起来很混乱。

我已经看过Issue with 'StringVar' in Python Program中的答案,但是我不知道如何将StringVar()与for循环和列表一起使用。

我正在使用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

谢谢!

1 个答案:

答案 0 :(得分:1)

使用字典。

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

现在在要使用变量varlist["customer_id"]的地方使用customer_id