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

使用grid布局的Tkinter Text组件如何获取编辑后的数据?

解决Tkinter Text组件内容更新numpy数组的问题

你的核心问题是没有保存每个Text组件的引用,循环中每次创建的text变量会被下一次循环覆盖,且text.grid[0][0].get()是错误用法——grid是布局方法,并非存储组件的结构。以下是可行的解决方案:

步骤1:保存Text组件引用

创建一个二维列表,存储所有Text组件的实例,方便后续通过索引访问:

import tkinter as tk
import numpy as np

# 假设_6m是已初始化的5x6 numpy数组
_6m = np.random.rand(5, 6)

root = tk.Tk()
# 创建二维列表存储Text组件
text_widgets = []

for x in range(5):
    row_widgets = []
    for y in range(6):
        text = tk.Text(root, width=7, height=2)
        text.grid(row=x, column=y)
        text.insert(tk.END, round(_6m[x][y], 2))  # 保留两位小数显示
        row_widgets.append(text)
    text_widgets.append(row_widgets)

步骤2:编写更新数组的函数

遍历存储的Text组件,获取编辑后的内容并更新到_6m数组:

def update_6m_array():
    for x in range(5):
        for y in range(6):
            # 获取Text内容,去掉换行符和首尾空白
            content = text_widgets[x][y].get("1.0", tk.END).strip()
            # 转换为数组对应的数值类型(这里假设是float)
            try:
                _6m[x][y] = float(content)
            except ValueError:
                # 处理非数字输入,可根据需求调整默认值
                _6m[x][y] = 0.0
    print("更新后的_6m数组:")
    print(_6m)

# 添加按钮触发更新
update_btn = tk.Button(root, text="更新数组", command=update_6m_array)
update_btn.grid(row=5, column=0, columnspan=6, pady=10)

root.mainloop()

关键说明

  • Text组件获取内容的正确方式是text.get("1.0", tk.END):"1.0"表示文本起始位置(第1行第0列),tk.END表示文本末尾。
  • .strip()用于移除内容末尾的默认换行符和多余空格,避免转换数值时出错。
  • 加入try-except块处理非数字输入,防止程序崩溃,你可以根据实际需求修改错误处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:27:12