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

为何Tkinter下拉框输出{}Main而非Main?JSON读取异常排查

为啥你的Combobox里会多出个{}?

别着急,这个问题很好解决,根源出在你给Combobox赋值选项的方式上。

看你循环里的这段代码:

profiles_select['values'] = (profiles_select['values'], add_profile)

ttk.Combobox的values属性,当你读取它的时候返回的是元组(哪怕你初始化时传的是空列表)。第一次循环时,profiles_select['values']是空元组(),你把它和add_profile拼成了一个新的嵌套元组:((), 'Main')。Tkinter在渲染这个嵌套结构时,把最外层的空元组显示成了{},这就是你看到的多余符号的由来。第二次循环又会把这个嵌套元组和Test拼成更复杂的结构,结果自然不对。

两种解决办法任你选

方法一:先收集所有选项,一次性赋值(推荐)

这种方式最简洁,也不容易出错:

with open('profiles.txt', 'r') as file:
    profiles = json.load(file)

# 把所有profile_name提取到一个列表里
profile_list = [item['profile_name'] for item in profiles]
# 直接把整个列表赋值给Combobox的values
profiles_select['values'] = profile_list

方法二:循环里逐个追加(如果需要动态添加的话)

要是你必须在循环里逐个添加选项,记得先把当前的values转成列表,添加新元素后再赋值回去:

with open('profiles.txt', 'r') as file:
    profiles = json.load(file)

# 先把现有选项转成列表
current_options = list(profiles_select['values'])
for profile in profiles:
    current_options.append(profile['profile_name'])
# 最后一次性赋值
profiles_select['values'] = current_options

试一下上面的方法,下拉框就能正常显示Main和Test两个选项啦。

内容的提问来源于stack exchange,提问作者user10593699

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:32:42