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

PySimpleGUI切换窗口布局时无法自适应调整尺寸问题求助

问题:PySimpleGUI切换布局后窗口无法自适应尺寸

我的PySimpleGUI应用通过按钮点击切换不同布局(隐藏/显示不同Column),但切换后窗口无法根据新布局的元素自适应调整尺寸。比如从包含输入框和按钮的布局1切换到带Table的布局2时,Table显示尺寸远小于预期。尝试过在事件中更新窗口尺寸,但没有效果,附上代码求助:

import PySimpleGUI as sg
from database import *

sg.set_options(font=("Courier", 12))

#get all added records from database
records = getRecords()
print(records)

#check if inputs are empty
def checkMissingInput(lst):
    for i in lst:
        if i == '':
            return True
    return False

#create window to add records
def main():
    #root/main layout
    addRecordsLayout = [
        [sg.Push(), sg.Text("Password Manager"), sg.Push()],
        [sg.Text("URL "), sg.Push(), sg.Input("www.apple.com",enable_events=True, key="input-url")],
        [sg.Text("Username/Email "), sg.Push(), sg.Input("johndoe@gmail.com",enable_events=True, key="input-username")],
        [sg.Text("Password "), sg.Push(), sg.Input("john123",enable_events=True, key="input-password")],

        [sg.Button("Add Record", enable_events=True, key="add-records", expand_x=True), 
         sg.Button("Show Records", enable_events=True, key="show-records", expand_x=True), 
         sg.Button("Clear", enable_events=True, key="clear", expand_x=True)]
    ]

    #second layout, for viewing table of records
    toprows = ["Id","Url","Username","Password"]
    showRecordsLayout = [
        [sg.Push(),sg.Text("Records"),sg.Push()],
        [sg.Push(),sg.Table(key='records-table',values=records, headings=toprows, 
                  expand_x=True,
                  expand_y=True,
                  justification="center",
                  auto_size_columns=True,
                  enable_click_events=True 
                  ),sg.Push()],
        [sg.Button("Select",key="select-records",expand_x=True,enable_events=True),
         sg.Button("Exit",key="exit-show-records",expand_x=True,enable_events=True)]
    ]

    #third layout, for viewing selected layout from table
    showSelectedRecordLayout = [
        #[sg.Text(f"Record {selectRecordId}")]
        [sg.Text("Url: ")],
        [sg.Text("Username: ")],
        [sg.Text("Password: ")],

        [sg.Button("Delete", expand_x=True, key="delete-record-button"),
         sg.Button("Return", expand_x=True, key="exit-selected-record")]
    ]

    rootLayout = [[sg.Column(addRecordsLayout, key="column-1", visible=True)],
                  [sg.Column(showRecordsLayout, key="column-2", visible=False)],
                  [sg.Column(showSelectedRecordLayout, key="column-3", visible=False)]]

    window = sg.Window("Password Manager", rootLayout)
    while True:
        event, values = window.read()
    
        #events
        if event == sg.WIN_CLOSED:
            print(event)
        
            break
        elif event == 'clear':
            window['input-url'].update('')
            window['input-username'].update('')
            window['input-password'].update('')

        elif event == 'add-records':
            inputElementValues = list(values.values()) #get list all values in input elements
            try:
                if checkMissingInput(inputElementValues) == True:
                    sg.popup("Missing input values...")
                else:
                    addDbRecord(inputElementValues[0], inputElementValues[1], inputElementValues[2]) #add list of input values to database table
                    sg.popup("Record succesfully added...")

            except ValueError:
                print("ValueError")
        
        elif event == 'show-records':
            window["column-1"].update(visible=False)
            window["column-2"].update(visible=True)
            window['records-table'].update(values=getRecords()) #update records table to display new added records based on whats in database table

        if event == 'exit-show-records':
            window["column-1"].update(visible=True)
            window["column-2"].update(visible=False)

        elif event == 'select-records':
            window["column-2"].update(visible=False)
            window["column-3"].update(visible=True)
            print(values['records-table'])
        
        elif event == 'exit-selected-record':
            window["column-2"].update(visible=True)
            window["column-3"].update(visible=False)
    window.close()

if __name__ == "__main__":
    main()

解决方案

1. 调整Column的基础配置

给每个sg.Column添加size=(None, None)和pad=(0,0),让Column能根据内部元素自动计算尺寸,同时避免额外间距干扰布局计算:

rootLayout = [
    [sg.Column(addRecordsLayout, key="column-1", visible=True, size=(None, None), pad=(0,0))],
    [sg.Column(showRecordsLayout, key="column-2", visible=False, size=(None, None), pad=(0,0))],
    [sg.Column(showSelectedRecordLayout, key="column-3", visible=False, size=(None, None), pad=(0,0))]
]

2. 切换布局后触发窗口自适应

在每次切换布局的事件处理中,先刷新窗口,再让Tkinter自动计算并应用布局的合适尺寸。通过window.TKroot.geometry("")可以实现这一点:

修改show-records事件:

elif event == 'show-records':
    window["column-1"].update(visible=False)
    window["column-2"].update(visible=True)
    window['records-table'].update(values=getRecords())
    # 刷新并自适应窗口
    window.refresh()
    window.TKroot.geometry("")

同理修改其他切换事件:

if event == 'exit-show-records':
    window["column-1"].update(visible=True)
    window["column-2"].update(visible=False)
    window.refresh()
    window.TKroot.geometry("")

elif event == 'select-records':
    window["column-2"].update(visible=False)
    window["column-3"].update(visible=True)
    print(values['records-table'])
    window.refresh()
    window.TKroot.geometry("")

elif event == 'exit-selected-record':
    window["column-2"].update(visible=True)
    window["column-3"].update(visible=False)
    window.refresh()
    window.TKroot.geometry("")

3. 优化Table元素显示效果

给Table添加num_rows属性,设置初始显示的行数,让Table默认有足够的高度:

sg.Table(key='records-table',values=records, headings=toprows, 
         expand_x=True,
         expand_y=True,
         justification="center",
         auto_size_columns=True,
         enable_click_events=True,
         num_rows=10  # 按需求调整行数
         )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:59:54