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

如何在PySimpleGUI中重复生成X个带不同Key的相同布局?

高效生成带唯一Key的重复布局(PySimpleGUI)

问题概述

编写程序时遇到核心问题:如何重复生成X个结构相同的布局,且每个布局内的元素Key各不相同?原本打算预先创建100个布局,再根据数据量控制显隐,但希望找到更高效的实现方式。

解决方案思路

无需预先创建固定数量的布局,而是通过循环动态生成布局,给每个元素的Key添加唯一索引标识(比如-GRAPH-0、-GRAPH-1),后续更新时也通过循环批量处理,避免重复编写冗余代码。

具体实现步骤

  1. 修改布局生成函数,接收索引参数,生成带唯一Key的元素
  2. 循环调用该函数X次,批量构建完整布局
  3. 在超时更新逻辑中,通过循环遍历每个索引,统一处理数据更新和显隐控制

完整代码示例

import PySimpleGUI as sg

def get_selections_layouts(index):
    GSIZE = (80, 50)
    # 给每个元素的Key添加索引,确保唯一性
    graph = sg.Graph(GSIZE, (0, 0), GSIZE, key=f'-GRAPH-{index}-', background_color='blue')
    graph1 = sg.Graph(GSIZE, (0, 0), GSIZE, key=f'-GRAPH1-{index}-', background_color='pink')
  
    layoutSelections = sg.Column([
        [sg.T("Data", key=f'-DATASET-{index}-', justification='left'), sg.Push(), graph, graph1],
        [sg.HorizontalSeparator(pad=(0, 10))]
    ], expand_x=True)  

    return layoutSelections

# 设置要生成的布局数量X
X = 5
# 循环生成X个带唯一Key的布局
layout_selections_list = [get_selections_layouts(i) for i in range(X)]

# 构建主布局
dataHeading = sg.Text("数据集标题")
start_time_text = sg.Text("开始时间: --:--:--")
data_total = sg.Text("总数据量: 0")
layoutCol = sg.Column([])  # 可根据实际需求填充内容

layoutDataset = [
    [dataHeading],
    [start_time_text, data_total],
    [layoutCol],
    [sg.HorizontalSeparator()],
    # 将所有生成的布局加入主布局
    *[[layout] for layout in layout_selections_list]
]    

window = sg.Window("动态布局示例", layoutDataset)

while True:
    event, values = window.read(timeout=1000)  # 设置超时触发更新
    if event == sg.WIN_CLOSED:
        break
    elif event == sg.TIMEOUT_KEY:
        # 模拟获取当前数据,每组数据对应一个布局的两个graph内容
        currentSituation = [
            ("数据1-0", "数据2-0"),
            ("数据1-1", "数据2-1"),
            ("数据1-2", "数据2-2"),
            ("数据1-3", "数据2-3"),
            ("数据1-4", "数据2-4")
        ]
        
        # 循环处理每个布局的更新
        for i in range(X):
            try:
                data1 = currentSituation[i][0]
                window[f'-GRAPH-{i}-'].update(visible=True)
                # 清除旧内容后绘制新文本
                window[f'-GRAPH-{i}-'].erase()
                window[f'-GRAPH-{i}-'].draw_text(
                    data1, 
                    (GSIZE[0]//2, GSIZE[1]//1.5), 
                    font=('Any 20', 14),
                    text_location=sg.TEXT_LOCATION_CENTER, 
                    color='white'
                )
            except IndexError:
                window[f'-GRAPH-{i}-'].update(visible=False)
            
            try:
                data2 = currentSituation[i][1]
                window[f'-GRAPH1-{i}-'].update(visible=True)
                window[f'-GRAPH1-{i}-'].erase()
                window[f'-GRAPH1-{i}-'].draw_text(
                    data2, 
                    (GSIZE[0]//2, GSIZE[1]//3), 
                    font=('Any 40', 8),
                    text_location=sg.TEXT_LOCATION_CENTER, 
                    color='white'
                )
            except IndexError:
                window[f'-GRAPH1-{i}-'].update(visible=False)

window.close()

关键优化点

  • 动态Key生成:使用f-string给每个元素的Key添加索引,确保每个布局的元素Key唯一
  • 批量生成布局:通过列表推导式一次性生成X个布局,代码简洁高效
  • 批量更新逻辑:循环处理所有布局的显隐和数据更新,避免重复编写大量try/except块
  • 按需绘制文本:每次更新前先清除graph中的旧内容,避免新旧文本重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:16:32