Tkinter Python中的多个组合框 [英] Multiple ComboBoxes in Tkinter Python

查看:42
本文介绍了Tkinter Python中的多个组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用"config.ini"文件中的值生成多个组合框,config.ini文件中的数据为:

优先级1 =正常:farty-blobble-fx.wav:2
优先级8 = Reclamacao:buzzy-blop.wav:3
优先级3 = Critico:farty-blobble-fx.wav:5
priority2 = Urgente:echo-blip-thing.wav:4

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

并且我无法在组合框中显示"config.ini"文件的当前值.预先谢谢你.

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

推荐答案

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

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

这篇关于Tkinter Python中的多个组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆