2

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()
2
  • 1
    Are you aware you don't have to use StringVars with entry widgets? Unless you're using the same variable for more than one widget, you don't need them at all. Commented Sep 17, 2015 at 21:42
  • I recommend taking a loot at the Entry API, specifically the parts about delete and insert. Commented Sep 17, 2015 at 21:43

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

Comments

3

Just store them in a list.

vars = []
for i in range(height): #Rows
    for j in range(width): #Columns
        vars.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 in range(height): #Rows
    entries.append([])
    for j in range(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')

Comments

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.