Error while getting the index from an empty Listbox .get_indexes()

  listbox, pysimplegui, python, python-3.x

When I want to get the index of a selected item in a listbox, and the listbox is empty i get a error.

window['Listbox'].get_indexes()[0]
------------------------------------
IndexError: tuple index out of range

The original list that I use in my program is not empty, but it’s changing so it may be empty and in that case when I press on the listbox the program crashes.

Code:

import PySimpleGUI as sg

list1 = []

layout = [[sg.Listbox(list1, s=(13, 6), enable_events=True, key='Listbox')]]

window = sg.Window("listbox test 1", layout=layout, size=(100, 100))


while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
    if event == 'Listbox':
        print(window['Listbox'].get_indexes()[0])

Is there maybe a simple fix for that?

If no, then I’d have to add a check if the listbox is empty or no.

Source: Python-3x Questions

LEAVE A COMMENT