Reputation: 93
I would like to know if I can get a clue for this.
I receive a recordset from a table, whose fields are id, desc.
I would like to show the "values" on a combobox, but the variable I want to receive after a selection is the correspondent "id".
I can create a list with the id, and a list with desc
I can send "values" to the combo, but ... how can i una a combobox for showing the values and receiving the 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()
I get an error with choices!
Thank you
Upvotes: 2
Views: 8097
Reputation: 101
Based on Reid his answer I coded this new combobox class, but in a way that the get() method is still available. Thought I would share it for those looking for a similar thing:)
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)]
Upvotes: 2
Reputation: 1525
My first thought is to use a dictionary instead of lists. If you have the two lists for other reasons, you can turn them into a dictionary via:
ids = ['Hello', 'World', 'Foo', 'Bar']
vals = [64, 8, 4, 2]
mydict = dict(list(zip(ids,vals)))
Once you have the dictionary, you can use mydict[combobox.get()] when you query the combobox. If you're going to need this functionality in several other places, then you may want to create a custom version of the Combobox, a 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()
And then just use the 'value()' method instead of 'get()'
Upvotes: 4