You need to enable JavaScript to run this app. 如何从Python Tkinter生成的Entry表单表格中获取全部数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python Tkinter生成的Entry表单表格中获取全部数据?

问题根因

你代码的错误出现在tcompile函数的遍历逻辑中:你将所有Entry对象都存入了my_entries列表,但遍历的时候没有使用每次循环拿到的Entry实例,而是一直调用全局的cell变量取值——cell在创建表格的循环结束后只会指向最后生成的那个Entry控件,所以你只能读取到最后一个单元格的数值。

修正方案

只需要修改tcompile函数内的遍历逻辑,将循环内的cell.get()替换为当前遍历到的entries.get()即可,同时可以添加输入合法性校验避免非数字输入报错,完整修正代码如下:

import tkinter as tk
import matplotlib.pyplot as plt
graphinput = tk.Tk()
def opentable():
    global total_rows
    global total_columns
    total_rows = int(yaxis.get())
    total_columns = int(xaxis.get())
    table = tk.Toplevel(graphinput)
    def tcompile():
        masterlines = []   
        for entries in my_entries:
            # 改用当前遍历到的Entry对象取值
            current_val = entries.get()
            # 非空校验避免空输入报错
            if current_val.strip():
                masterlines.append(int(current_val))
        plt.plot(masterlines)
        plt.show()
    my_entries = []
    for i in range(total_rows):
        for j in range(total_columns):
            cell = tk.Entry(table,width=20,font=('Agency FB',15))
            cell.grid(row=i,column=j)
            my_entries.append(cell)
    tblframe = tk.Frame(table,bd=4)
    tblframe.grid(row=i+1,column=j)
    compbtn = tk.Button(tblframe,font=("Agency FB",20),text="Compile",command=tcompile)
    compbtn.grid(row=0,column=0)
tablegrid = tk.Frame(graphinput,bd=4)
tablegrid.pack()
xlabel = tk.Label(tablegrid,text="Column Entry")
xlabel.grid(row=0,column=0)
ylabel = tk.Label(tablegrid,text="Row Entry")
ylabel.grid(row=0,column=1)
xaxis = tk.Entry(tablegrid)
xaxis.grid(row=1,column=0)
yaxis = tk.Entry(tablegrid)
yaxis.grid(row=1,column=1)
framebtn = tk.Button(tablegrid,text="Create",command=opentable)
framebtn.grid(row=3,column=0)
graphinput.mainloop()
拓展说明

如果你后续需要按行/按维度处理表格数据,也可以在创建Entry的时候用二维列表存储,方便后续分维度读取:

# 二维列表存储示例
my_entries = []
for i in range(total_rows):
    row_entries = []
    for j in range(total_columns):
        cell = tk.Entry(table,width=20,font=('Agency FB',15))
        cell.grid(row=i,column=j)
        row_entries.append(cell)
    my_entries.append(row_entries)

读取的时候嵌套遍历即可按行取数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 16:30:03