繁体   English   中英

从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()

每次按下按钮“添加新行”都会创建一行四个文本框。 “打印值”按钮将一一打印所有文本框的值。 由于文本框是动态命名的,因此名称是字符串类型。 但是,观察“获取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对象,这就是为什么它仍然可以工作的原因。

暂无
暂无

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

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