如何在PySimpleGUI中获取ComboBox的当前选中索引?
PySimpleGUI ComboBox 获取选中项索引的解决方案
PySimpleGUI的ComboBox本身没有提供直接获取选中项索引的API,但可以通过以下两种方式实现需求:
方法1:通过选中值匹配选项列表获取索引
利用你从SQLite查询得到的选项列表,在事件处理中通过值匹配的方式获取对应索引。
示例代码:
import PySimpleGUI as sg import sqlite3 # 从SQLite读取选项列表 conn = sqlite3.connect('your_db.db') cursor = conn.cursor() cursor.execute("SELECT option_content FROM your_table") options = [row[0] for row in cursor.fetchall()] conn.close() # 构建GUI布局 layout = [ [sg.Combo(options, key='-COMBO-', enable_events=True)], [sg.Text('选中项索引:', key='-INDEX_DISPLAY-')], [sg.Button('退出')] ] window = sg.Window('ComboBox索引获取', layout) while True: event, values = window.read() if event in (sg.WIN_CLOSED, '退出'): break if event == '-COMBO-': selected_val = values['-COMBO-'] if selected_val in options: idx = options.index(selected_val) window['-INDEX_DISPLAY-'].update(f'选中项索引:{idx}') else: window['-INDEX_DISPLAY-'].update('选中项索引:无') window.close()
注意:如果选项列表存在重复值,index()方法仅会返回第一个匹配项的索引。若需获取所有匹配项的索引,可改用枚举遍历:
matched_indices = [i for i, val in enumerate(options) if val == selected_val]
方法2:建立值与索引的映射字典
如果需要关联数据库原生索引(比如表的主键ID),可以在查询时同时获取索引和选项文本,构建值到索引的映射字典,直接通过选中值快速查找对应索引。
示例代码:
import PySimpleGUI as sg import sqlite3 # 从SQLite读取选项文本和对应主键ID conn = sqlite3.connect('your_db.db') cursor = conn.cursor() cursor.execute("SELECT id, option_content FROM your_table") rows = cursor.fetchall() conn.close() options = [row[1] for row in rows] val_to_db_idx = {row[1]: row[0] for row in rows} # 构建值到数据库索引的映射 # 构建GUI布局 layout = [ [sg.Combo(options, key='-COMBO-', enable_events=True)], [sg.Text('数据库索引:', key='-DB_INDEX_DISPLAY-')], [sg.Button('退出')] ] window = sg.Window('ComboBox索引获取', layout) while True: event, values = window.read() if event in (sg.WIN_CLOSED, '退出'): break if event == '-COMBO-': selected_val = values['-COMBO-'] db_idx = val_to_db_idx.get(selected_val, '无') window['-DB_INDEX_DISPLAY-'].update(f'数据库索引:{db_idx}') window.close()
内容的提问来源于stack exchange,提问作者Eduardo C.
相关产品推荐
相关产品推荐

