01 July 2023

PySimpleGUI use image as button and toggle it too

When I wanted to use an image as a button in PySimpleGUI, I was led to an example that used a massive image and linked to code somewhere else which wrote base64 encoded strings into a file. It didn't have to be this difficult, so I simplified it and also added code to toggle the button images.

You can use these images as the play.png and pause.png. I created them with Inkscape.


The code

import base64
import PySimpleGUI as simpleGUI
    
if __name__ == '__main__':
    themeName = 'Dark'
    simpleGUI.theme(themeName)
    #Note: background color is what helps the button's transparent portion seem invisible
    backgroundColorOfGUI = simpleGUI.LOOK_AND_FEEL_TABLE[themeName]['BACKGROUND']
    hoverColor = 'grey'

    PLAYPAUSE = '-playpause-'
    PLAY_ICON = 'play.png'
    PAUSE_ICON = 'pause.png'
    buttonText = ''
    icons = dict()
    WINDOW_WAIT_TIMEOUT_MILLISECOND = 100
    
    #---images need to be converted to base64 strings to be used as buttons
    imagesToLoad = [PLAY_ICON, PAUSE_ICON]
    for image in imagesToLoad:
        contents = open(image, 'rb').read()
        encodedString = base64.b64encode(contents)
        icons[image] = encodedString

    basicLayout = [                        
                    [simpleGUI.Button(buttonText, key = PLAYPAUSE,
                                        image_data = icons[PAUSE_ICON],
                                        button_color = (hoverColor, backgroundColorOfGUI),
                                        border_width = 0,
                                        metadata = False)],
                  ]
    windowTitle = 'Toggle Button'
    window = simpleGUI.Window(windowTitle, layout = basicLayout)
    while True:                
        event, values = window.read(timeout = WINDOW_WAIT_TIMEOUT_MILLISECOND)      
        #---toggle button image on click
        if event == PLAYPAUSE:
            element = window[event]
            if element.metadata:
                element.update(image_data=icons[PAUSE_ICON])                
            else:
                element.update(image_data=icons[PLAY_ICON])                
            element.metadata = not element.metadata  
        #---detect close window event
        if event == simpleGUI.WIN_CLOSED or event == simpleGUI.Exit:
            window.close()            
            break
    print("Program ended")           

            
           


No comments: