You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Tkinter循环创建的Entry值并存储为二维数组

解决RREF计算器中获取Entry值为空数组的问题

问题根源

你在创建矩阵Entry时,直接将它们grid到setupMatrix框架中,因此setupMatrix.winfo_children()返回的就是所有Entry组件本身,而非按行分组的嵌套框架。原solveMatrix函数中错误地尝试访问每个子元素的子组件(winfo_children()[i].winfo_children()),但Entry没有子组件,导致获取不到值,最终返回空数组。

快速修正方案

直接通过grid_slaves方法根据行列位置获取对应Entry,确保顺序正确:

def solveMatrix(setupMatrix):
    rowSize = int(rowCombo.get())
    colSize = int(colCombo.get())
    matrix_values = []
    for i in range(rowSize):
        row_values = []
        for j in range(colSize):
            # 获取对应行列位置的Entry
            entry = setupMatrix.grid_slaves(row=i, column=j)[0]
            # 可添加数值转换逻辑,比如转为float
            value = entry.get()
            row_values.append(value)
        matrix_values.append(row_values)
    print(matrix_values)

更可靠的优化方案

在创建Entry时直接存储引用到二维列表,避免依赖布局查询,提升代码稳定性:

  1. 修改Table类,新增存储Entry的属性:
class Table:
    def __init__(self):
        self.entries = []  # 存储所有Entry的二维列表

    def setCol(self, setupMatrix):
        # 清空旧的Entry和存储列表
        self.entries.clear()
        for widget in setupMatrix.winfo_children():
            widget.destroy()
            
        colSize = int(colCombo.get())
        rowSize = int(rowCombo.get())

        for i in range(rowSize):
            row_entries = []
            for j in range(colSize):
                entry = Entry(setupMatrix, width=5, fg='blue', font=('Arial', 16, 'bold'))
                entry.grid(row=i, column=j)
                row_entries.append(entry)
            self.entries.append(row_entries)
  1. 修改solveMatrix函数,直接使用存储的Entry引用:
def solveMatrix():
    matrix_values = []
    for row_entries in table_instance.entries:
        row_values = []
        for entry in row_entries:
            value = entry.get()
            # 处理空输入或非数值情况,转为float类型
            try:
                row_values.append(float(value))
            except ValueError:
                row_values.append(0.0)  # 可根据需求调整默认值
        matrix_values.append(row_values)
    print(matrix_values)
  1. 更新按钮的command参数,无需传递setupMatrix:
solveButton = tb.Button(root, text="Solve Matrix", bootstyle=DEFAULT, command=solveMatrix)

完整修正代码

from tkinter import *
from ttkbootstrap.constants import *
import ttkbootstrap as tb
import os

os.environ['TK_SILENCE_DEPRECATION'] = '1'

root = tb.Window(themename="solar")  # dark mode
# root = tb.Window(themename="cerculean") # light mode

root.title("RREF CALCULATOR")

root.geometry('1000x800')
root.resizable(False, False)
mytitle = tb.Label(text="Find the RREF of a Matrix from 2x2 to 5x5", font=('helvetica', 29), bootstyle=DEFAULT)

setup = tb.Frame(root, bootstyle=DEFAULT)
setup.place(x=400, y=150)

setupMatrix = tb.Frame(root)
setupMatrix.place(x=150, y=450)

# labels for row and col,
row = tb.Label(setup, text="Enter number of Rows", font=('helvetica', 18), bootstyle=DEFAULT)
col = tb.Label(setup, text="Enter number of Columns", font=('helvetica', 18), bootstyle=DEFAULT)

matrixSize = ["2", "3", "4", "5"]

myButton = tb.Button(setup, text="Create matrix", bootstyle=DEFAULT, command=lambda: setCol(setupMatrix))
resetButton = tb.Button(setup, text="Reset", bootstyle=DEFAULT, command=lambda: resetMatrix(setupMatrix, rowCombo, colCombo))
solveButton = tb.Button(root, text="Solve Matrix", bootstyle=DEFAULT, command=solveMatrix)
# dropdowns for the size of the matrix
colCombo = tb.Combobox(setup, bootstyle=DEFAULT, values=matrixSize)
colCombo.current(0)
rowCombo = tb.Combobox(setup, bootstyle=DEFAULT, values=matrixSize)
rowCombo.current(0)

row.pack(pady=5)
rowCombo.pack(pady=5)
col.pack(pady=5)
colCombo.pack(pady=10)
myButton.pack(side=LEFT)
resetButton.pack(side=RIGHT)
mytitle.pack(pady=50)
solveButton.pack(pady=310)

class Table:
    def __init__(self):
        self.entries = []  # 存储所有Entry的二维列表

    def setCol(self, setupMatrix):
        # 清空旧的Entry和存储列表
        self.entries.clear()
        for widget in setupMatrix.winfo_children():
            widget.destroy()
            
        colSize = int(colCombo.get())
        rowSize = int(rowCombo.get())

        for i in range(rowSize):
            row_entries = []
            for j in range(colSize):
                entry = Entry(setupMatrix, width=5, fg='blue', font=('Arial', 16, 'bold'))
                entry.grid(row=i, column=j)
                row_entries.append(entry)
            self.entries.append(row_entries)

def setCol(setupMatrix):
    table_instance.setCol(setupMatrix)

def resetMatrix(setupMatrix, rowCombo, colCombo):
    table_instance.entries.clear()
    for widget in setupMatrix.winfo_children():
        widget.destroy()
    rowCombo.set('')  # Clear the selected value in the combobox
    colCombo.set('')  # Clear the selected value in the combobox

def solveMatrix():
    matrix_values = []
    for row_entries in table_instance.entries:
        row_values = []
        for entry in row_entries:
            value = entry.get()
            # 处理空输入或非数值情况
            try:
                row_values.append(float(value))
            except ValueError:
                row_values.append(0.0)
        matrix_values.append(row_values)
    print(matrix_values)

# Create an instance of the Table class
table_instance = Table()

root.mainloop()

内容的提问来源于stack exchange,提问作者Gabriele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:01:05