Python如何从对象生成GUI字符串列表:PySimpleGUI动态下拉选项问题
问题根因
prepare_dropdown_categories() 函数的返回值本身就是字符串列表,你在传给psg.Combo的第一个参数时额外套了一层[],相当于把整个列表当成单个元素塞入新列表,最终传给下拉框的可选值是[[name0, name1, name2...]]的二维结构,PySimpleGUI解析时会把内层列表强制转为字符串拼接展示,就出现了你看到的大括号包裹的拼接内容。
修复方法
- 核心修改:去掉Combo参数外层多余的列表包裹,直接传入函数返回的列表即可
- 可选优化:提前捕获API请求异常,做兜底逻辑,同时保证默认值
All crimes存在于可选列表中
修改后代码示例
gui.py
import PySimpleGUI as psg import prep_data # 提前获取下拉选项,增加异常处理兜底 try: category_options = prep_data.prepare_dropdown_categories() # 将默认选项加入可选列表,避免默认值不在选项中的异常 if "All crimes" not in category_options: category_options.insert(0, "All crimes") except: # API请求失败时的兜底选项 category_options = ["All crimes"] layout = [ [psg.Text('Choose category:', size=(20, 1), font='Lucida', justification='left')], # 直接传入获取到的列表,不需要额外加[] [psg.Combo(category_options, default_value='All crimes', key='all')], [psg.Button('SAVE', font=('Lucida', 12)), psg.Button('CANCEL', font=('Lucida', 12))] ]
prep_data.py(可选优化)
def prepare_dropdown_categories(): categories = [] try: fetched_categories = fetch_categories() # 从API获取数据,返回json.loads解析后的结果 for category in fetched_categories: categories.append(category['name']) except: # 请求异常时返回空列表,上层做兜底处理 pass return categories
内容的提问来源于stack exchange,提问作者Nati
相关产品推荐
相关产品推荐

