You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取PySimpleGUI Combo组件的values属性?

解决方案

在PySimpleGUI中,官方API确实没有直接提供获取Combo组件全部选项列表的方法,但可以通过访问其底层的tkinter组件来实现,无需手动维护外部的combo_list数组。

具体实现方式

PySimpleGUI的Combo组件封装了tkinter的ttk.Combobox,你可以通过.Widget属性获取到底层的tk组件,然后直接读取其values属性,这会返回当前组件中所有选项的元组,转成列表即可使用:

# 获取当前Combo的全部选项
current_options = list(window['-COMBO-'].Widget['values'])

完整示例代码

比如添加新选项的逻辑可以改成这样,不用再同步更新combo_list:

import PySimpleGUI as sg

# 初始化选项列表
combo_list = ['Choice 1', 'Choice 2']    
layout = [
    [sg.Combo(combo_list, default_value=combo_list[0], key='-COMBO-', enable_events=True)],
    [sg.Input(key='-NEW_ITEM-'), sg.Button('添加选项')],
    [sg.Button('退出并保存')]
]

window = sg.Window('Combo示例', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == '退出并保存':
        # 直接从组件读取当前所有选项
        current_options = list(window['-COMBO-'].Widget['values'])
        # 这里执行保存逻辑,比如写入文件
        print("保存的选项列表:", current_options)
        break
    if event == '添加选项':
        new_item = values['-NEW_ITEM-'].strip()
        if new_item:
            # 获取当前选项并添加新项
            current_options = list(window['-COMBO-'].Widget['values'])
            if new_item not in current_options:
                current_options.append(new_item)
                # 更新Combo组件的选项
                window['-COMBO-'].update(values=current_options)
                window['-NEW_ITEM-'].update('')

window.close()

注意事项

  • 这种方式依赖PySimpleGUI对tkinter组件的封装实现,目前各版本都兼容,但如果后续PySimpleGUI底层实现变更,可能需要调整。
  • 相比手动维护combo_list,这种方式能避免选项列表在组件和外部数组之间不同步的问题,逻辑更简洁。

如果官方后续推出直接获取选项列表的API,可以切换到官方方法,但目前这是最简便的替代方案。

内容的提问来源于stack exchange,提问作者Lee-xp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:54:56