我想知道我能不能找到线索。
我从一个表接收一个记录集,该表的字段是id、desc。
我想在组合框上显示“值”,但是在选择后要接收的变量是对应的"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()我的选择是错误的!
谢谢
发布于 2014-05-27 23:50:25
我的第一个想法是使用字典而不是列表。如果出于其他原因,您有这两个列表,则可以通过以下方法将它们转换为字典:
ids = ['Hello', 'World', 'Foo', 'Bar']
vals = [64, 8, 4, 2]
mydict = dict(list(zip(ids,vals)))一旦有了字典,就可以在查询组合框时使用mydictcombobox.get()。如果您需要在其他几个地方使用这个功能,那么您可能需要创建一个自定义的Combobox版本,即la:
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()’
发布于 2016-07-14 12:34:25
基于Reid的答案,我编写了这个新的combobox类,但在某种程度上,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)]https://stackoverflow.com/questions/23732065
复制相似问题