15.6 PySimpleGUI Events

The Event Loop

All GUIs have one thing in common, an "event loop". Usually the GUI framework runs the event loop for you, but sometimes you want greater control and will run your own event loop. You often hear the term event loop when discussing embedded systems or on a Raspberry Pi.

With PySimpleGUI if your window will remain open following button clicks, then your code will have an event loop. If your program shows a single "one-shot" window, collects the data and then has no other GUI interaction, then you don't need an event loop.

There's nothing mysterious about event loops... they are loops where you take care of.... wait for it..... events. Events are things like button clicks, key strokes, mouse scroll-wheel up/down.

This little program has a typical PySimpleGUI Event Loop.

The anatomy of a PySimpleGUI event loop is as follows, generally speaking.


import PySimpleGUI as sg
import os

def main():
    # Build a list of tuples for each file type the file dialog should display
    my_filetypes = (('all files', '.*'), ('text files', '.txt'))

    # Ask the user to select a single file name for saving.
    layout = [[sg.Text('Please select a file name for saving:'),
               sg.FileSaveAs(initial_folder=os.getcwd(), file_types=my_filetypes, key='-SAVE-'),
               sg.Button('OK'), sg.Button('Cancel')]]

    window = sg.Window('Save as...', layout)

    # this is the event loop
    while True:
        event, values = window.read()

        if event == sg.WIN_CLOSED or event == 'Cancel':
            break
        elif event == 'OK':
            if values['-SAVE-']:
                write_file(values['-SAVE-'])
            break

    window.close()


def write_file(file):
    # code to write to file goes here
    print(f'code to write to \"{file}\" file goes here')


if __name__ == '__main__':
    main()
      


window.read() activates the window to interact with the user. Two values are returned: event and values. event indicates why (which button was pressed) the read completed, and values is a dictionary of inputs from the user. Dictionary keys can be set using the key= keyword on user inputs. Here, key='-SAVE-' is used for the sg.FileSaveAs element. If no keys are set, values will be a list. It's best to use keys on all of your input type elements. Click to read more about PySimpleGUI events.

In the event loop, action can be taken based on events and values using conditionals. Here, the function write_file() is being called when a file has been chosen by the user. This is one way to implement so-called "callback" functions.