ttk.combobox 选项列表

2 投票
2 回答
7946 浏览
提问于 2025-04-18 06:58

我想知道我能否得到一些线索。

我从一个表格中获取了一组记录,这个表格的字段有id和desc。

我想在一个下拉框(combobox)中显示这些“值”,但是我希望在选择后能得到对应的“id”。

我可以分别创建一个id的列表和一个desc的列表。

我可以把“值”发送到下拉框中,但是……我该怎么做才能让下拉框显示这些值,并且在选择后能接收到id呢?

def loadCombo(self):    
    sql = "SELECT id, desc FROM table"
    misq = conn.query2(sql)
    misc , misv = [] , []
    for xx in misq:
        misv.append(xx["desc"])
        misc.append(xx["id"])`

    self.box = ttk.Combobox(self.master, textvariable=self.idquiniela, state="readonly", choices=misc, values=misv )
    self.box.pack()

我在选择时遇到了错误!

谢谢!

2 个回答

2

根据Reid的回答,我写了一个新的下拉框类,但我保留了get()方法。觉得这个对那些想要类似功能的人可能会有帮助,所以分享出来:)

from tkinter.ttk import Combobox

class NewCombobox(Combobox):
    """
    Because the classic ttk Combobox does not take a dictionary for values.
    """

    def __init__(self, master, dictionary, *args, **kwargs):
        Combobox.__init__(self, master,
                          values=sorted(list(dictionary.keys())),
                          *args, **kwargs)
        self.dictionary = dictionary

    def get(self):
        if Combobox.get(self) == '':
            return ''
        else:
            return self.dictionary[Combobox.get(self)]
4

我首先想到的是用字典来代替列表。如果你有两个列表是出于其他原因存在的,可以通过以下方式把它们转换成字典:

ids = ['Hello', 'World', 'Foo', 'Bar']
vals = [64, 8, 4, 2]
mydict = dict(list(zip(ids,vals)))

一旦你有了字典,当你查询下拉框时,可以使用mydict[combobox.get()]。如果你在其他地方也需要这个功能,可能想要创建一个自定义的下拉框,像这样:

from tkinter import Tk
from tkinter import ttk

class NewCBox(ttk.Combobox):
    def __init__(self, master, dictionary, *args, **kw):
        ttk.Combobox.__init__(self, master, values = sorted(list(dictionary.keys())), state = 'readonly', *args, **kw)
        self.dictionary = dictionary
        self.bind('<<ComboboxSelected>>', self.selected) #purely for testing purposes

    def value(self):
        return self.dictionary[self.get()]

    def selected(self, event): #Just to test
        print(self.value())

lookup = {'Hello': 64, 'World' : 8, 'Foo': 4, 'Bar': 2}
root = Tk()
newcb = NewCBox(root, lookup)
newcb.pack()

然后只需使用'value()'方法,而不是'get()'

撰写回答