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

如何基于子串条件修改PySimpleGUI表格行颜色?

PySimpleGUI表格根据列子串动态修改行背景色

要实现根据指定列的子串匹配结果修改对应行背景色,核心是遍历表格数据筛选目标行,再通过Table.Update(row_colors)应用样式。以下是针对需求的完整实现:

实现步骤

  1. 遍历表格每行数据,检查目标列(示例中为第1列Name,索引为1)的内容是否包含指定子串"Ra";
  2. 收集所有符合条件的行索引,整理成row_colors要求的格式:[[行索引, 背景色], ...];
  3. 调用表格组件的Update方法,传入row_colors参数完成样式设置;
  4. 若需要动态更新(比如用户输入新子串后重新匹配),可在事件循环中重复上述逻辑。

修改后的完整代码

import PySimpleGUI as psg
psg.set_options(font=("Arial Bold", 14))

toprow = ['S.No.', 'Name', 'Age', 'Marks']
rows = [[1, 'Rajeev', 23, 78],
        [2, 'Rajani', 21, 66],
        [3, 'Rahul', 22, 60],
        [4, 'Robin', 20, 75]]

# 初始化表格组件
tbl1 = psg.Table(values=rows, headings=toprow,
                 auto_size_columns=True,
                 display_row_numbers=False,
                 justification='center', key='-TABLE-',
                 selected_row_colors='red on yellow',
                 enable_events=True,
                 expand_x=True,
                 expand_y=True,
                 enable_click_events=True)

layout = [[tbl1]]
window = psg.Window("Table Demo", layout, size=(715, 200), resizable=True)

# 初始化时设置行背景色
target_substring = "Ra"
target_column_index = 1  # 对应Name列
row_colors = []

for row_idx, row_data in enumerate(rows):
    # 检查目标列是否包含子串(注意大小写敏感,如需忽略可转小写后比较)
    if target_substring in str(row_data[target_column_index]):
        row_colors.append([row_idx, 'green'])  # 设置背景色为绿色

# 更新表格行颜色
window['-TABLE-'].Update(row_colors=row_colors)

while True:
    event, values = window.read()
    print("event:", event, "values:", values)
    if event == psg.WIN_CLOSED:
        break
    if '+CLICKED+' in event:
        psg.popup("You clicked row:{} Column: {}".format(event[2][0], event[2][1]))
    # 可在此添加动态触发逻辑,比如用户输入新子串后重新计算row_colors并更新

window.close()

关键说明

  • 大小写敏感:如果需要忽略大小写匹配,可修改判断逻辑为target_substring.lower() in str(row_data[target_column_index]).lower();
  • 文字颜色设置:若要同时修改文字颜色,可使用"文字色 on 背景色"的格式,比如'white on green';
  • 动态更新:如果需要在程序运行中根据用户操作(如输入框输入新子串)重新匹配,只需在对应事件中重新生成row_colors并调用Update即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:25:31