PySimpleGUI Combo: Bind key/value pair array or get selected index?

Question:

I’m really astounded that there doesn’t seem to be a way to bind a dictionary or key/value pair array to a simple dropdownlist that the Combo element is supposed to cover. The contents of a given Combo in my app is fetched from the database and I would like to know the primary key of any item that is selected from said Combo. However, it only seems possible to populate the Combo with a list of strings, so everytime I tried to "get" the item, the name string is all I’ve got left.

A temporary workaround where I fetch the source item from the database based on the name string is tenuous at best, as there’s no guarantee that I’m getting the actual item and not some alternative that happens to have the same name. Also, it would be unneccesary to do another database trip, when you’ve already just fetched all the items!

A more reliable workaround where I keep the table rows in memory and then look up the row using the selected index, also falls short, because, in contrast with pysimplegui’s Listbox element, you cannot get the selected item’s index of a Combo!!!

What gives!? I’m about to completely give up on PySimpleGUI in favour of a (hopefully) better alternative. If you know of any, I would regard that as an answer to my question also.


EDIT: Thanks to Jason Yang’s Answer I arrived at the following:

import PySimpleGUI as sg

# Internal 
import data_access as db
import util

collections = db.getRows('collection')
collList = util.convert_dbrow_list(collections)

layout = [[sg.Text('collections'), sg.Combo(collList, enable_events=True, key='cbxCollections', size=(30, 1))],]
window = sg.Window('testing', layout)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event =='cbxCollections':
        text = values[event]
        index = window[event].widget.current()
        id = collections[index]['id'] 
        spid = collections[index]['spid'] 
        print(index, id, spid, repr(values[event]))

window.close()
Asked By: Fedor Steeman

||

Answers:

You can use method current() for the widget of Combo element, or index the value of entry from the value list of Combo element.

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'):
        text = values['COMBO']
        index1 = window['COMBO'].widget.current()
        index2 = data.index(text) if text in data else -1
        print(index1, index2, repr(values['COMBO']))

window.close()
Answered By: Jason Yang