问题描述
我有一个小脚本,可以生成随机数量的条目小部件.每个都需要一个 StringVar() 以便我可以将文本分配给小部件.我如何将这些创建为循环的一部分,因为我不会提前知道会有多少?
I have a small script that generates a random number of entry widgets. Each one needs a StringVar() so I can assign text to the widget. How can I create these as part of the loop since I won't know ahead of time as to how many there will be?
from Tkinter import *
import random
root = Tk()
a = StringVar()
height = random.randrange(0,5)
width = 1
for i in range(height): #Rows
value + i = StringVar()
for j in range(width): #Columns
b = Entry(root, text="", width=100, textvariable=value+i)
b.grid(row=i, column=j)
mainloop()
推荐答案
直接回答您的问题是使用列表或字典来存储 StringVar
的每个实例.
The direct answer to your question is to use a list or dictionary to store each instance of StringVar
.
例如:
vars = []
for i in range(height):
var = StringVar()
vars.append(var)
b = Entry(..., textvariable=var)
但是,您不需要将 StringVar
与入口小部件一起使用.StringVar
如果您希望两个小部件共享同一个变量,或者如果您正在对变量进行跟踪,那么 StringVar
是很好的,否则它们会增加开销而没有真正的好处.
However, you don't need to use StringVar
with entry widgets. StringVar
is good if you want two widgets to share the same variable, or if you're doing traces on the variable, but otherwise they add overhead with no real benefit.
entries = []
for i in range(height):
entry = Entry(root, width=100)
entries.append(entry)
您可以使用insert
和delete
方法插入或删除数据,并使用get
获取值:
You can insert or delete data with the methods insert
and delete
, and get the value with get
:
for i in range(height):
value = entries[i].get()
print "value of entry %s is %s" % (i, value)
这篇关于在循环中为 Tkinter 条目小部件创建 StringVar 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!