Get the current index of a combobox in pysimplegui?

Viewed 68

I have a combobox with options that are gathered from a SQLite table, and I am trying to get the index from this combobox when the user selects an option. I have tried to use it like a table but to no avail... It seems that combo boxes have an Index in Pysimplegui because you can use update(set_to_index=), but I can't seem to find a way to access it anywhere. Can anyone help?

2 Answers

There's no method provided for it now in PySimpleGUI.

With tkinter method current, you can get the index of the current entry text in the values list, or -1 if the current entry text is not in the values list.

import PySimpleGUI as sg

data = ['One', 'Two', 'Three', 'Four']
layout = [
    [sg.Combo(data, size=20, enable_events=True, key='COMBO')],
    [sg.Push(), sg.Button('Check')],
]
window = sg.Window('Title', layout)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break
    elif event in ('COMBO', 'Check'):
        index = window['COMBO'].widget.current()
        print(index)

window.close()

There is a Combo.get method if needed, but you really shouldn't need it as the values dictionary provides the same data.

Here's how to get the index using the values variable.

import PySimpleGUI as sg

choices = ['aaa', 'bbb', 'ccc']
layout = [  [sg.Combo(choices, k='-COMBO-')],
            [sg.Button('Go'), sg.Button('Exit')]  ]

window = sg.Window('Window Title', layout)

while True:
    event, values = window.read()
    print(event, values)
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'Go':
        if values['-COMBO-'] in choices:
            idx = choices.index(values['-COMBO-'])
            print(f'Index = {idx}')
        else:
            print('Selection not in choices')

window.close()

enter image description here

Here's the get method in use. You can also simply use values['-COMBO-'] It will return the current value. You can then use that to look up the "index" from the original choices.

import PySimpleGUI as sg

choices = ['aaa', 'bbb', 'ccc']
layout = [  [sg.Combo(choices, k='-COMBO-')],
            [sg.Button('Go'), sg.Button('Exit')]  ]

window = sg.Window('Window Title', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'Go':
        current = window['-COMBO-'].get()
        if current in choices:
            idx = choices.index(current)
            print(f'Index = {idx}')
        else:
            print('Selection not in choices')

window.close()
Related