Creating Stringvar Variables In A Loop For Tkinter Entry Widgets
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 s
Solution 1:
The direct answer to your question is to use a list or dictionary to store each instance of StringVar
.
For example:
vars = []
for i in range(height):
var = StringVar()
vars.append(var)
b = Entry(..., textvariable=var)
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)
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)
Solution 2:
Just store them in a list
.
vars = []
for i inrange(height): #Rowsfor j inrange(width): #Columnsvars.append(StringVar())
b = Entry(root, text="", width=100, textvariable=vars[-1])
b.grid(row=i, column=j)
That said, you should probably be storing the Entry
widgets themselves in a list
, or a 2D list
as shown:
entries = []
for i inrange(height): #Rows
entries.append([])
for j inrange(width): #Columns
entries[i].append(Entry(root, text="", width=100))
entries[i][j].grid(row=i, column=j)
You can then assign text to each widget with the insert()
method:
entries[0][3].insert(0, 'hello')
Post a Comment for "Creating Stringvar Variables In A Loop For Tkinter Entry Widgets"