[英]PySimpleGUI Combo: Bind key/value pair array or get selected index?
我真的很驚訝,似乎沒有辦法將字典或鍵/值對數組綁定到 Combo 元素應該覆蓋的簡單下拉列表。 我的應用程序中給定組合的內容是從數據庫中獲取的,我想知道從所述組合中選擇的任何項目的主鍵。 但是,似乎只能用字符串列表填充 Combo,所以每次我嘗試“獲取”該項目時,我只剩下名稱字符串。
我根據名稱字符串從數據庫中獲取源項目的臨時解決方法充其量是微不足道的,因為不能保證我得到的是實際項目,而不是碰巧具有相同名稱的替代品。 此外,當您剛剛獲取所有項目時,無需再進行一次數據庫之旅!
一個更可靠的解決方法是,我將表行保留在 memory 中,然后使用選定的索引查找行,但也不足,因為與 pysimplegui 的 Listbox 元素相比,您無法獲得 Combo 的選定項目的索引!
是什么賦予了?。 如果您知道的話,我將完全放棄 PySimpleGUI 以支持(希望)更好的選擇。 我也認為這是對我問題的回答。
編輯:感謝Jason Yang 的回答,我得出以下結論:
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()
您可以對 Combo 元素的小部件使用current()
方法,或者從 Combo 元素的值列表中索引條目的值。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.