I can't use the Menu in PySimpleGUI

Viewed 1064

I want to add a feature to change the background using the menu but it doesn't work. When I click on any menu item, nothing happens, the background doesn't change and it doesn't print anything. Maybe I'm also doing the background change in a wrong way, so, if someone could help me, I would be happy.

This is my code:

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()
2 Answers

On this line:

if menu_def == 'purple':

The variable menu_def is a whole list, it cannot be equal to purple. I believe you meant to say if event == 'Purple'?

Use 'Menu item::optional_key' as event in your event loop.

There're sub-menu under menu, so no easy setting for background color of all items in menu.

There're something wrong in your code

  • Method sg.theme(theme)only work before window finalized
  • Different value of user variable theme won't change the theme state.
  • Method window.refresh() is not required if next statement will be window.read() which will update window.

For new theme and new setting for Menu, new window will be preferred. Demo code as following,

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()
Related