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

PySimpleGUI嵌套在Column内的Button点击无响应如何解决

问题根因

你代码里的按钮无响应和嵌套布局无关,是Button组件的参数传错导致的:

  • PySimpleGUI的sg.Button()第二个位置参数是key,你误将对齐提示字符串"center"传到了key的位置,导致两个按钮的key都被设为相同的"center",冲突后事件无法正常识别触发。
  • "center"并不是Button的合法位置参数,如果你要实现按钮居中对齐,应该通过Column的element_justification参数控制列内元素对齐,而非传递给Button。
修复后的代码
import PySimpleGUI as sg

# 移除Button的多余位置参数,对齐逻辑统一放到Column配置中
layout1 = [[sg.Button('New')], [sg.Button("Load Save")]]
layout2 = [[sg.Text("2nd Page")], [sg.Button("New Page")], [sg.Button("Load Page")]]

# 通过element_justification='center'实现列内所有元素居中
layout = [[sg.Column(layout1, key='-COL1-', element_justification='center'), 
           sg.Column(layout2, visible=False, key='-COL2-', element_justification='center')]]

window = sg.Window('ORIGINAL').Layout(layout)

while True:             # 事件循环
    event, values = window.Read()
    if event in (None, 'Exit'):
        break
    if event == 'New':
        print("hello")
    elif event == 'Load Save':
        print("load save触发")
    elif event == 'New Page':
        # 示例切换第二页的逻辑
        window['-COL1-'].update(visible=False)
        window['-COL2-'].update(visible=True)
window.Close()
补充注意事项

如果后续需要给按钮自定义key,必须显式传参,不要随意填写位置参数避免匹配错误:
sg.Button('按钮显示文本', key='-CUSTOM-BTN-KEY-')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:48:02