简体   繁体   English

访问使用for循环创建的Entry小部件

[英]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 ) ? 如何访问每个条目以更新其值(例如,使用StringVar)?

You could create a list of lists for your Entry widgets. 您可以为Entry窗口小部件创建列表列表。

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] . 然后,您可以将各个条目称为“ 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. 编辑:要编辑条目小部件e的文本,请首先使用e.delete(0, END)清除它,然后使用e.insert(0, "new text")插入新文本。

Edit2: Alternatively, you could store the StringVars in a list of lists instead of the widgets... Edit2:或者,您可以将StringVars存储在列表列表中,而不是小部件中。

You need to first declare the StringVar variable: 您需要首先声明StringVar变量:

myvar = StringVar()

Then in your loop whenever you want to check to content of the variable use the get() method. 然后在循环中,每当您要检查变量的内容时,请使用get()方法。

x = myvar.get()

Now x will hold the value. 现在x将保留该值。 You can also perform a bool test with if 您还可以执行一个布尔测试if

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

In that if statement the program checks if there is data in the var. 在该if语句中,程序检查var中是否有数据。 If not it will move on 如果没有,它将继续前进

Looking at it again you should also declare the StringVar() in your button. 再次查看它,您还应该在按钮中声明StringVar() Like so: 像这样:

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

Look Here for more info 在这里查看更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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