Web Analytics Made Easy - Statcounter
Skip to content

Highly Responsive Inputs

Sometimes it's desireable to begin processing input information when a user makes a selection rather than requiring the user to click an OK button.

Let's say you've got a listbox of entries and a user can select an item from it.

import PySimpleGUI as sg

choices = ('Red', 'Green', 'Blue', 'Yellow', 'Orange', 'Purple', 'Chartreuse')

layout = [  [sg.Text('What is your favorite color?')],
            [sg.Listbox(choices, size=(15, len(choices)), key='-COLOR-')],
            [sg.Button('Ok')]  ]

window = sg.Window('Pick a color', layout)

while True:                  # the event loop
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    if event == 'Ok':
        if values['-COLOR-']:    # if something is highlighted in the list
            sg.popup(f"Your favorite color is {values['-COLOR-'][0]}")
window.close()

image

When you choose a color and click OK, a popup like this one is shown:

image

Use enable_events to instantly get events

That was simple enough. But maybe you're impatient and don't want to have to cick "Ok". Maybe you don't want an OK button at all. If that's you, then you'll like the enable_events parameter that is available for nearly all elements. Setting enable_events means that like button presses, when that element is interacted with (e.g. clicked on, a character entered into) then an event is immediately generated causing your window.read() call to return.

If the previous example were changed such that the OK button is removed and the enable_events parameter is added, then the code and window appear like this:

import PySimpleGUI as sg

choices = ('Red', 'Green', 'Blue', 'Yellow', 'Orange', 'Purple', 'Chartreuse')

layout = [  [sg.Text('What is your favorite color?')],
            [sg.Listbox(choices, size=(15, len(choices)), key='-COLOR-', enable_events=True)] ]

window = sg.Window('Pick a color', layout)

while True:                  # the event loop
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    if values['-COLOR-']:    # if something is highlighted in the list
        sg.popup(f"Your favorite color is {values['-COLOR-'][0]}")
window.close()

image

You won't need to click the OK button anymore because as soon as you make the selection in the listbox the read() call returns and the popup will be displayed as before.

This second example code could be used with the OK button. It doesn't matter what event caused the window.read() to return. The important thing is whether or not a valid selection was made. The check for event == 'Ok' is actually not needed.