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

Time:11-26

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.

CodePudding user response:

May this work in your case?

if event == 'Listbox':
   try:
      print(window['Listbox'].get_indexes()[0])
   except:
      print("Empty list")

CodePudding user response:

All that's required is an if statement.

if values['Listbox']:    # if something was selected
   first_entry = values['Listbox'][0]
   window['Listbox'].get_indexes()[0]  # if you want the index... it'll be safe because values says there are entries


  • Related