Reputation: 19
I have a tkinter combobox populated by a dictionary with two fields: name, id. Using a callback function I can get the name field, but I need the ID field.
var_person = tk.StringVar()
cb = ttk.Combobox(root, values=list(my_dict.keys()),
textvariable=var_person)
cb.grid(row=0, column=1)
def callback(event):
a = var_person.get()
print (a)
cb.bind('<<ComboboxSelected>>', callback)
Results: Prints the selected name, but I really need the id.
Thanks for any assistance.
John
Forgot to show the bind method
Upvotes: 0
Views: 610
Reputation: 15088
Does this example give you an idea? Nothing much is done, the combobox data is taken and the corresponding value from the dictionary is returned.
from tkinter import *
from tkinter import ttk
root = Tk()
def callback():
key = var_person.get()
try: #To bypass the error when user chooses nothing
value = my_dict[key] #get the corresponding value from the given key
print(value) #print it
except KeyError:
print('Please choose an option') #error message
my_dict = {'Allen, Jamie': 2,
'Anderson, Abbie': 1391, 'Anderson, Marcie': 1380}
var_person = StringVar()
cb = ttk.Combobox(root, values=list(my_dict.keys()), textvariable=var_person)
cb.current(1) #setting the current value to index position 1 of the list(optional)
cb.pack(pady=10,padx=10)
b = Button(root,text='Click me',command=callback).pack(pady=10,padx=10)
root.mainloop()
Let me know if any doubts :D
Cheers
Upvotes: 1