PySimpleGUI 改变可见性打破列(?)

PySimpleGUI changing visibility breaks columns(?)

我有 2 列,我想通过使用可见性参数在按下按钮时显示它们。但是,从不可见到可见的列似乎不再彼此相邻,而是像行一样排列。

这是没有显示的代码,列工作正常:

import PySimpleGUI as sg

left_col = sg.Column([[sg.Frame('',[],background_color = '#FF0000',size = (60,40))]])
right_col = sg.Column([[sg.Frame('',[],background_color = '#00FF00',size = (60,40))]])

layout = [
    [sg.Button('reveal')],
    [left_col,right_col]]

window = sg.Window('Converter', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

window.close()

下面是显示列的相同代码:

import PySimpleGUI as sg

left_col = sg.Column([[sg.Frame('',[],background_color = '#FF0000',size = (60,40))]],visible = False, key = 'left')
right_col = sg.Column([[sg.Frame('',[],background_color = '#00FF00',size = (60,40))]],visible = False, key = 'right')

layout = [
    [sg.Button('reveal')],
    [left_col,right_col]]

window = sg.Window('Converter', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    if event == 'reveal':
        window['left'].update(visible = True)
        window['right'].update(visible = True)
        
window.close()

我想我的问题是是否有解决方法(或者我是否做错了什么)。

visible=False 之后的元素将丢失其在 window 中的位置,因此如果您想将其设置为不可见,请使用函数 pin 保留元素的位置。

layout = [
    [sg.Button('reveal')],
    [sg.pin(left_col), sg.pin(right_col)]]

背景默认为主题背景色。当然你也可以自己建一个,多一个选项 bg as background_color.

不要忘记同时在布局中设置 Column 的背景颜色。

def pin(elem, vertical_alignment=None, shrink=True, expand_x=None, expand_y=None, bg=None):
    if shrink:
        return sg.Column([[elem, sg.Column([[]], pad=(0,0), background_color=bg)]], background_color=bg, pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y)
    else:
        return sg.Column([[elem]], pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y, background_color=bg)

然后你的代码可能是这样的

import PySimpleGUI as sg

def pin(elem, vertical_alignment=None, shrink=True, expand_x=None, expand_y=None, bg=None):
    if shrink:
        return sg.Column([[elem, sg.Column([[]], pad=(0,0), background_color=bg)]], background_color=bg, pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y)
    else:
        return sg.Column([[elem]], pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y, background_color=bg)


left_col = sg.Column([[sg.Frame('',  [], background_color = '#FF0000', size = (60,40))]], background_color='blue')
right_col = sg.Column([[sg.Frame('', [], background_color = '#00FF00', size = (60,40))]], background_color='blue')

layout = [
    [sg.Button('reveal')],
    [pin(left_col, bg='blue'), pin(right_col, bg='blue')]]

window = sg.Window('Converter', layout, background_color='blue')

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

window.close()