简体   繁体   中英

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 ) ?

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 eg 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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM