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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With