guyd
guyd

Reputation: 733

Accessing Entry widget created using for loop

An array of Entries was created using the following code

from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

for i in range(height): #Rows
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)

mainloop()

How do I access each Entry to update its value ( using StringVar - for example ) ?

Upvotes: 1

Views: 2350

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

You could create a list of lists for your Entry widgets.

from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

entries = []

for i in range(height): #Rows
  newrow = []
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)
    newrow.append(b)
  entries.append(newrow)

mainloop()

You could then address individual entries as e.g. entries[2][4].

Edit: To edit the text of entry widget e, first use e.delete(0, END) to clear it, and then use e.insert(0, "new text") to insert new text.

Edit2: Alternatively, you could store the StringVars in a list of lists instead of the widgets...

Upvotes: 5

Joe
Joe

Reputation: 2997

You need to first declare the StringVar variable:

myvar = StringVar()

Then in your loop whenever you want to check to content of the variable use the get() method.

x = myvar.get()

Now x will hold the value. You can also perform a bool test with if

if myvar.get():
     print(myvar.get())

In that if statement the program checks if there is data in the var. If not it will move on

Looking at it again you should also declare the StringVar() in your button. Like so:

b = Button(text='clickme', texvariable=myvar)

Look Here for more info

Upvotes: 0

Related Questions