Armen Halajyan
Armen Halajyan

Reputation: 97

How do I set the values of tkinter combobox from dictionary keys

root = Tk()
my_dict = {'Drosophila melanogaster':1
           'Danio rerio': 2,
           'Caenorhabditis elegans':3,
           'Rattus norvegicus': 4,
           'Mus musculus': 5,
           'Homo sapiens': 6,
           }
combobox_values = "\n".join(my_dict.keys())
organism = ttk.Combobox(root, values=combobox_values) 
organism.grid(row=2, column=0, sticky="w", padx=2, pady=2)

I am trying to use each dictionary key as an option in the combobox, but when I run my script, each word becomes a separate option. I would really appreciate if someone could tell me what I am doing wrong?

Upvotes: 4

Views: 4783

Answers (2)

Grant
Grant

Reputation: 1

try combobox_values = list(my_dict.keys()) as I did not get the expected result with python 3.8

Upvotes: 0

en_Knight
en_Knight

Reputation: 5371

You were very close!

combobox_values = "\n".join(my_dict.keys())

should be

combobox_values = my_dict.keys()

By using join, you take all of the keys from the dictionary and then put them in one string! When Tkinter tries to delineate your string, it decides that spaces are just as good as the newlines for breaking up the items.


It was a little tricky to actually track down the delineation used under the hood. The official docs don't mention

Checking the source code Combobox inherits from the Entry widget, but both make raw calls to the underlying tcl. New Mexico (usually reputable) claims the values need to be in a list, but clearly a string works too. Since strings and lists are very similar in python, the fail-slow approach ttk takes seems appropriate... but it doesn't answer the question...

In fact, here's a fun game: try and break the constructor. Pass a random number? The following all work

ttk.Combobox(root, values=12345) 
class Foo:pass
ttk.Combobox(root, values=Foo())
ttk.Combobox(root, values=Foo)

After further investigation, the final python call happens on line 2058 of Tkinter.py (or so, implementation dependent). If your really curious, you can trace down from the tcl docs into their detailed widgets section, specifically the chapter "Keeping Extra Item Data" to see how and why these things happen like they do

In the latter two, the display method makes it clear, that the input is being wrapped as its own string representation (in keeping with New Mexico's interpretation), but the underlying method remains evasive

Upvotes: 9

Related Questions