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

如何修改PySimpleGUI表格的值?解决列与索引显示异常

PySimpleGUI表格更新:正确传递数据并动态修改列名

核心问题分析

  • PySimpleGUI的Table组件不支持直接传入Pandas DataFrame,必须转换成列表的列表格式
  • 直接调用values.tolist()会丢失索引列(STAT项),需要手动将索引合并到每一行数据中
  • 初始列名是固定3列,而生成后的表格需要动态列名,必须同步更新headings参数

解决方案步骤

1. 转换DataFrame为Table兼容的列表格式

把final_df的索引(统计项名称)和每一行数值合并,生成包含STAT列的结构化行数据:

# 遍历DataFrame的索引和行,将索引作为第一列加入每行数据
table_rows = [[index] + row.tolist() for index, row in final_df.iterrows()]

2. 生成动态列名列表

根据数据库名称生成新的表头,第一个固定为"STAT",后续为数据库名称:

new_headings = ["STAT"] + df_names.tolist()

3. 同步更新表格的内容和表头

在GENERATE事件中,替换原有的update代码,同时更新values和headings:

window["-TABLE-"].update(values=table_rows, headings=new_headings)

4. 修正初始表格的基础设置

初始的data应该用列表而非集合(集合无序会导致表格行顺序混乱),同时修正Q2为Q3(与list_variables保持一致):

data= [
  ["Count", "-", "-"],
  ["Average", " -", "-"],
  ["Median", "-", "-"],
  ["Min", " -", "-"],
  ["Max", "-", "-"],
  ["StdDev", " -", "-"],
  ["Q1", "-", "-"],
  ["Q3", " -", "-"],
]

完整修正后的GENERATE事件代码

while True:
    event, values = window.read()  # 补充原代码缺失的read()逻辑
    if event == sg.WIN_CLOSED:
        break
    if event == 'GENERATE':
        selection(file_list)
        file_loc2 = (real_path + "/minimum.csv")
        try:
            archive = pd.read_csv(file_loc2, sep=",")
            df_names = pd.unique(archive["survey"])
            dicts = {}  # 每次生成前清空字典,避免旧数据残留
            for name in df_names:
                dicts[name] = pd.DataFrame(
                    data=archive.loc[archive["survey"] == name],
                    columns=("Wavelength_(nm)", "survey")
                )
            
            final = {}  # 初始化统计结果字典
            tablegen(dicts)
            
            final_df = pd.DataFrame(data=final, index=list_variables, columns=df_names)   
            final_df = final_df.round(decimals=1)
            
            # 转换为Table兼容格式
            table_rows = [[idx] + row.tolist() for idx, row in final_df.iterrows()]
            new_headings = ["STAT"] + df_names.tolist()
            
            # 更新表格
            window["-TABLE-"].update(values=table_rows, headings=new_headings)
            
        except Exception as E:
            print(f'** Error {E} **')
            pass

额外注意事项

  • 每次点击GENERATE时,要清空dicts和final字典,避免之前的计算结果残留
  • 原代码中缺失window.read()逻辑,必须补充才能触发事件循环
  • tablegen函数中的final变量需要提前初始化,否则会报未定义错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:45:51