Tkinter Python中的多个ComboBox

时间:2015-12-17 11:29:46

标签: python combobox tkinter

我正在尝试使用“config.ini”文件中的值生成多个ComboBox,config.ini文件数据为:

priority1 =正常:farty-blobble-fx.wav:2
priority8 = Reclamacao:buzzy-blop.wav:3
priority3 = Critico:farty-blobble-fx.wav:5
priority2 = Urgente:echo-blip-thing.wav:4

目标是将声音文件名称转换为组合框中的选择值。

GUI

生成组合框的代码是:

content_data = []
for name, value in parser.items(section_name):
    if name=="name":
        self.note.add(self.tab2, text = value)
    else:
        data_prior = value.split(":")
        self.PRIOR_LABEL = Label(self.tab2, text=data_prior[0])
        self.PRIOR_LABEL.grid(row=data_prior[2],column=0,pady=(10, 2),padx=(40,0))

        self.PRIOR_SOUNDS = None
        self.PRIOR_SOUNDS = None
        self.box_value = StringVar()
        self.PRIOR_SOUNDS = Combobox(self.tab2, textvariable=self.box_value,state='readonly',width=35)
        self.PRIOR_SOUNDS['values'] = getSoundsName()
        self.PRIOR_SOUNDS.current(int(getSoundsName().index(data_prior[1])))
        self.PRIOR_SOUNDS.grid(row=data_prior[2],column=1,pady=(10, 2),padx=(30,0))

        self.PLAY = Button(self.tab2)
        self.PLAY["width"] = 5
        self.PLAY["text"] = "Play"
        self.PLAY["command"] =  lambda:playSound(self.PRIOR_SOUNDS.get())
        self.PLAY.grid(row=data_prior[2], column=3,pady=(10,2),padx=(5,0))

我无法在组合框中显示“config.ini”文件的当前值。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题在于您创建了多个组合框,但是在循环的每次迭代中都会覆盖变量。在循环结束时,self.PRIOR_SOUNDS将始终指向您创建的最后一个组合框。 self.box_valueself.PLAY等也是如此。

最简单的解决方案是使用数组或字典来存储所有变量。字典允许您按名称引用每个窗口小部件或变量;使用列表可以按顺序位置引用它们。

使用字典的解决方案看起来像这样:

self.combo_var = {}
self.combo = {}
for name, value in parser.items(section_name):
    ...
    self.combo_var[name] = StringVar()
    self.combo[name] = Combobox(..., textvariable = self.combo_var[name])
    ...