为何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
相关产品推荐
相关产品推荐

