Multiple ComboBoxes in Tkinter Python

Deadly 提交于 2020-12-26 12:12:21

问题


I'm trying to generate multiple ComboBoxes with values from a "config.ini" file, the config.ini file data is:

priority1 = Normal: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

and the goal is turning the sound files names to the select values in the comboboxes.

My code to generate the comboboxes is:

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))

And i was unable to show the current values of the "config.ini" file in the comboboxes. Thank you in advance.


回答1:


The problem is that you're creating more than one combobox, yet you keep overwriting the variables in each iteration of the loop. At the end of the loop, self.PRIOR_SOUNDS will always point to the last combobox that you created. The same is true for self.box_value, self.PLAY, etc.

The simplest solution is to use an array or dictionary to store all of your variables. A dictionary lets you reference each widget or variable by name; using a list lets you reference them by their ordinal position.

A solution using a dictionary would look something like this:

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])
    ...


来源:https://stackoverflow.com/questions/34333493/multiple-comboboxes-in-tkinter-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!