从 tkinter 中的多个文本框获取值
Getting values from multiple textboxes in tkinter
我有以下代码。
from Tkinter import *
root = Tk()
n_array = [] #will be used as 2d array
def add_four_entries():
global root, n_array
row_array=[] #array used to store a row
n_array.append(row_array)
y=len(n_array)
for x in range(4):
tbn="t"+str(y)+str(x) #create entrybox names of the form t10, t11,...
#print(tbn)
tbn=Entry(root)
row_array.append(tbn)
row_array[x].grid(row=y, column=x,sticky="nsew", padx=2,pady=2)
def getval():
for row in range(len(n_array)):
for col in range(4):
tbn="t"+str(row+1)+str(col)
print(tbn.get())
Button(root, text="Add new row", command=add_four_entries).grid(row=0, column=1,)
Button(root, text="Print val", command=getval).grid(row=21, column=1,)
mainloop()
按钮 'add new row' 每次按下都会创建一行四个文本框。按钮 'Print Val' 将所有文本框的值一一打印出来。
由于文本框是动态命名的,因此名称是字符串类型。但是点击获取 Val 按钮时出现此错误。
AttributeError: 'str' object has no attribute 'get'
我做错了什么?
替换
for col in range(4):
tbn="t"+str(row+1)+str(col)
print(tbn.get())
和
for col in range(4):
print(n_array[row][col].get())
您不需要存储姓名。如果网格是按已知顺序构建的,您可以使用 n_array 索引(实际上是列表的列表)作为坐标以到达您保存的 Entry
控件。
你实际上是在丢弃 tbn
字符串
tbn=Entry(root)
但是您存储了 Entry 对象,这就是它仍然有效的原因。
我有以下代码。
from Tkinter import *
root = Tk()
n_array = [] #will be used as 2d array
def add_four_entries():
global root, n_array
row_array=[] #array used to store a row
n_array.append(row_array)
y=len(n_array)
for x in range(4):
tbn="t"+str(y)+str(x) #create entrybox names of the form t10, t11,...
#print(tbn)
tbn=Entry(root)
row_array.append(tbn)
row_array[x].grid(row=y, column=x,sticky="nsew", padx=2,pady=2)
def getval():
for row in range(len(n_array)):
for col in range(4):
tbn="t"+str(row+1)+str(col)
print(tbn.get())
Button(root, text="Add new row", command=add_four_entries).grid(row=0, column=1,)
Button(root, text="Print val", command=getval).grid(row=21, column=1,)
mainloop()
按钮 'add new row' 每次按下都会创建一行四个文本框。按钮 'Print Val' 将所有文本框的值一一打印出来。 由于文本框是动态命名的,因此名称是字符串类型。但是点击获取 Val 按钮时出现此错误。
AttributeError: 'str' object has no attribute 'get'
我做错了什么?
替换
for col in range(4):
tbn="t"+str(row+1)+str(col)
print(tbn.get())
和
for col in range(4):
print(n_array[row][col].get())
您不需要存储姓名。如果网格是按已知顺序构建的,您可以使用 n_array 索引(实际上是列表的列表)作为坐标以到达您保存的 Entry
控件。
你实际上是在丢弃 tbn
字符串
tbn=Entry(root)
但是您存储了 Entry 对象,这就是它仍然有效的原因。