1

How do I collect value in a listbox (sg.Listbox)? That is, when I select that line of the listbox (listbox 2, for example) with what parameters do I make the conditional?

For example:

[sg.Listbox(values=('Listbox 1', 'Listbox 2', 'Listbox 3','Listbox 4', 'Listbox 5'), key="_LISTBOX_"], [sg.Button('Option')]]

while True:             # Event Loop
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
if event == 'Option':
    print(values) #here I see the values but I have no idea what to do. !!!! ????

    if values["_LISTBOX_"??????]: #??????????
        print("ok")
    window['-OUTPUT-'].update()

1 Answer 1

3

To get information of selected items in sg.Listbox,

  • Get values of selected items from values['-LISTBOX-']
  • Get indexes of selected items from method get_indexes of sg.Listbox.
import PySimpleGUI as sg

value_list = [f'Listbox {i}' for i in range(1, 6)]
layout = [
    [sg.Listbox(value_list, size=(30, 5), font=("Courier New", 16), enable_events=True, key="-LISTBOX-")],
    [sg.StatusBar("", size=(30, 1), key='-STATUS-')],
]

window = sg.Window('Title', layout, finalize=True)
listbox, status = window['-LISTBOX-'], window['-STATUS-']

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    elif event == '-LISTBOX-':
        selection = values[event]
        if selection:
            item = selection[0]
            index = listbox.get_indexes()[0]
            status.update(f'Line {index+1}, "{item}" selected')

window.close()
3
  • 1
    Excuse me, thanks again, now one more step, ;-) I need to fix an image inside a frame when activating a list for example (if index == 0 :) and so when I activate any list I will insert a different image in that frame
    – Aikrana
    Commented Oct 2, 2021 at 13:43
  • 2
    Add more code if index == 0: window['-IMAGE-'].update(filename=image_files[0]) or window['-IMAGE-'].update(filename=image_files[index]) in block of elif event == '-LISTBOX-', window['-IMAGE-'] is the sg.Image element with option key='-IMAGE-' in your layout.
    – Jason Yang
    Commented Oct 2, 2021 at 14:08
  • Thank you very much again, it has been a great help to me
    – Aikrana
    Commented Oct 9, 2021 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.