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

如何在PySimpleGUI表格的sg.Input中添加key引用适配docxtpl

给PySimpleGUI表格输入框添加Key的解决方案

要给表格中的每个sg.Input添加唯一可识别的Key,核心思路是利用循环的行号和列号生成唯一标识,这样既能保证每个输入框的Key不重复,也方便后续精准定位操作。下面提供两种实用的实现方式:

方法1:使用元组作为Key(PySimpleGUI推荐方式)

元组是可哈希类型,能直观体现输入框的行列位置,代码简洁易维护:

headings = ['test1', 'test2', 'test3','test4','Result']
header =  [[sg.Text('  ')] + [sg.Text(h, size=(12)) for h in headings]]

# 生成带元组Key的输入行,Key格式为(行索引, 列索引)
input_rows = [[sg.Input(size=(10,1), pad=(20,0), key=(row, col)) for col in range(5)] for row in range(4)]

后续获取或修改输入值时,直接通过元组Key定位:

# 获取第2行第3列(索引从0开始)的输入值
target_value = window[(1, 2)].get()

方法2:使用格式化字符串作为Key(更直观的命名)

如果偏好字符串类型的Key,可以用f-string生成带行列标识的命名:

headings = ['test1', 'test2', 'test3','test4','Result']
header =  [[sg.Text('  ')] + [sg.Text(h, size=(12)) for h in headings]]

# 生成带字符串Key的输入行,Key格式为"INPUT_R{行号}_C{列号}"
input_rows = [[sg.Input(size=(10,1), pad=(20,0), key=f"INPUT_R{row}_C{col}") for col in range(5)] for row in range(4)]

对应取值方式:

# 获取第2行第3列(索引从0开始)的输入值
target_value = window["INPUT_R1_C2"].get()

完整示例代码

下面是包含布局、事件处理的完整脚本,可直接运行测试:

import PySimpleGUI as sg

headings = ['test1', 'test2', 'test3','test4','Result']
header =  [[sg.Text('  ')] + [sg.Text(h, size=(12)) for h in headings]]

# 选用元组Key的方式生成输入行
input_rows = [[sg.Input(size=(10,1), pad=(20,0), key=(row, col)) for col in range(5)] for row in range(4)]

# 组合完整布局
layout = header + input_rows + [[sg.Button('提交'), sg.Button('取消')]]

window = sg.Window('表格数据输入', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == '取消':
        break
    if event == '提交':
        # 遍历打印所有输入框的值
        for row in range(4):
            row_data = []
            for col in range(5):
                row_data.append(values[(row, col)])
            print(f"第{row+1}行数据: {row_data}")

window.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:28:20