python - 如何获取单个行的值?

标签 python python-3.x tkinter

我正在制作一个使用列表并具有 2 行和 5 列的程序。每个元素都是一个条目。我希望能够访问列表中整行的所有列。

当我一次访问所有行中的所有元素时,它起作用了。但是当我尝试获取单行的值时,它不起作用

这是有效的代码:

#Build the grid and append to the listCounter list.
for i in range(2):
    for x in range(5):
        entry = Entry(frame, text="", width=5)
        entry.grid(row=i, column=x)
        listCounter.append(entry)

#Get the value of every row
def btnClick():
    sum = 0
    for puntuation in listCounter:           
        sum += int(puntuation.get())
    print(sum)

但是当我尝试使用 listCounter[0] 获取单行的所有条目时,它不起作用:

def btnClick():
    sum = 0
    for puntuation in listCounter[0]:           
        sum += int(puntuation.get())
    print(sum)

我收到以下错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Rober\AppData\Local\Programs\Python\Python37- 
32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "D:/PyProjects/TestCanvas/Connect4.py", line 25, in btnClick
for puntuation in listCounter[0]:
File "C:\Users\Rober\AppData\Local\Programs\Python\Python37- 
32\lib\tkinter\__init__.py", line 1489, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str

所以我尝试获取有关 listCounter 的信息:

print(type(listCounter))   --> <class 'list'>
print(type(listCounter[0]) --> <class 'tkinter.Entry'>

这里到底是什么问题,我该如何解决?

最佳答案

如果你想创建一个合适的二维列表(一个列表的列表),你需要显式地创建嵌套元素:

for i in range(2):
    row = []
    for x in range(5):
        entry = Entry(frame, text="", width=5)
        entry.grid(row=i, column=x)
        row.append(entry)
    listCounter.append(row)

现在您将能够索引 listCounter[0] 并获取第一行的元素。以前,您将 listCounter 作为一个包含 10 个元素的列表,而 listCounter[0] 可以理解为只是一个 Entry 对象。

关于python - 如何获取单个行的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102747/

相关文章:

python - 装饰器不能与 yield 命令一起正常工作

python - 根据字符串分割二进制文件

python - 如何在 PyQt5 上使用 Vars,就像在 tkinter 上使用 IntVar() 或 StringVar() 一样?

python - 如何使用回车键调用按钮命令

python - 如何在等待套接字数据时使 tkinter 响应事件?

python - 具有多个组的正则表达式无法捕获括号

python - 通过 Python Socket Server 发送 HTML

python - pip3 install mysql-python 失败,错误代码为 1 in/tmp/pip-install-4nev4id4/mysql-python/

python - 从上到下阅读源代码时,装饰器是否总是按照遇到的顺序调用?

python-2.7 - TclError : wrong # args error