我无法在 PySimpleGUI 中使用菜单

I can't use the Menu in PySimpleGUI

我想添加一个功能来使用菜单更改背景,但它不起作用。当我点击任何菜单项时,没有任何反应,背景没有改变,也没有打印任何东西。也许我也以错误的方式进行了背景更改,所以,如果有人能帮助我,我会很高兴。

这是我的代码:

from time import sleep
import os
try:
    import PySimpleGUI as sg
except ModuleNotFoundError:
    os.system('pip3 install PySimpleGUI')
import sys

theme = ('dark grey 9')

sg.theme(theme)

menu_def = [['Customize GUI', ['Background', ['White::white', 'Purple::purple']]]]

layout = [[sg.Menu(menu_def)]]

window = sg.Window('Fast reader by Hary', layout)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    if event == 'Purple::purple':
        theme = 'LightPurple'
        window.refresh()
    elif event == 'White::white':
        theme = 'DarkGrey6'
        window.refresh()

这一行:

if menu_def == 'purple':

变量menu_def是一个完整的列表,不能等于purple。我相信你的意思是 if event == 'Purple'?

使用 'Menu item::optional_key' 作为事件循环中的事件。

菜单下有子菜单,所以菜单中所有项目的背景颜色不容易设置。

你的代码有问题

  • 方法sg.theme(theme)仅在window完成之前有效
  • 用户变量的不同值theme不会改变主题状态。
  • 如果下一个语句将是 window.read(),那么方法 window.refresh() 将不被要求,这将更新 window.

对于新主题和菜单的新设置,新的 window 将是首选。演示代码如下,

import PySimpleGUI as sg

def main_window(theme, background_color, window=None):

    sg.theme(theme)

    menu_def = [['Customize GUI', ['Background', ['White::white', 'Purple::purple']]]]
    layout = [[sg.Menu(menu_def, key='-MENU-', text_color='black', background_color=background_color)]]
    new_window = sg.Window('Fast reader by Hary', layout, finalize=True)
    if window is not None:
        window.close()
    return new_window

theme, background_color = 'DarkGrey9', 'green'
window = main_window(theme, background_color)

while True:

    event, values = window.read()

    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'Purple::purple':
        theme, background_color = 'LightPurple', 'purple'
        window = main_window(theme, background_color, window)
    elif event == 'White::white':
        theme, background_color = 'DarkGrey6', 'white'
        window = main_window(theme, background_color, window)

window.close()