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

PySimpleGUI隐藏元素后如何让窗口自动调整消除空白?

解决PySimpleGUI隐藏元素后窗口自适应调整大小的问题

问题核心在于:设置元素visible=False时,元素仅被隐藏但仍会占据原有布局空间,导致窗口无法自动收缩。要实现窗口在元素隐藏/显示时自适应调整,只需在修改元素可见性后调用window.size_yourself()方法,该方法会让窗口根据当前可见元素重新计算并适配最佳尺寸。

修改后的完整代码:

import PySimpleGUI as sg

# Define a custom theme for the GUI
my_new_theme = {'BACKGROUND': "#31363b",
                'TEXT': "#f9f1ee",
                'INPUT': "#232629",
                'TEXT_INPUT': "#f9f1ee",
                'SCROLL': "#333a41",
                'BUTTON': ('#31363b', '#0dd1fc'),
                'PROGRESS': ('#f9f1ee', '#31363b'),
                'BORDER': 1,
                'SLIDER_DEPTH': 0,
                'PROGRESS_DEPTH': 0}

# Add and set the custom theme
sg.theme_add_new("MyNewTheme", my_new_theme)
sg.theme("MyNewTheme")
sg.set_options(font=("Helvetica", 12))

layout = [
    [sg.Text("Input mesh name:", pad=(1, 5)), sg.InputText(key="mesh")],

    [sg.Text("Paste boundary conditions below:", pad=(1, 5))],
    [sg.Multiline(key="bound_cond", size=(35, 10), pad=(1, 5))],

    [sg.Radio(".csv", "RADIO1", default=True, key='-CSV-', enable_events=True, pad=(1, 5)),
     sg.Radio(".rsp", "RADIO1", key='-RSP-', enable_events=True, pad=(1, 5))],

    [sg.Text("Select .csv or .rsp file:", size=(17, 1)), sg.Input(), sg.FileBrowse("Choose")],

    [sg.Column([[sg.Text("Auto-assign:", size=(17, 1)), sg.Input(key='-FILE-'),
                 sg.FileBrowse("Choose")]], key='-NODE_FILE-', visible=False, pad=(0, 0))],
    [sg.Button("Create")]
]

window = sg.Window("Input Creation Wizard", layout=layout)

while True:
    event, values = window.read()

    match event:
        case sg.WIN_CLOSED:
            break

        case '-RSP-':
            window['-NODE_FILE-'].update(visible=True)
            window.size_yourself()  # 触发窗口自适应调整

        case '-CSV-':
            window['-NODE_FILE-'].update(visible=False)
            window.size_yourself()  # 触发窗口自适应调整

window.close()

补充说明

  • window.size_yourself()会自动计算当前可见元素所需的最小窗口尺寸,彻底消除隐藏元素留下的空白区域。
  • 若遇到窗口调整不流畅的情况,可在调用size_yourself()前先调用window.refresh(),确保元素状态更新后再调整窗口大小。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:29:49