如何从字典键设置 tkinter 组合框的值

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)

我试图将每个字典键用作组合框中的一个选项,但是当我 运行 我的脚本时,每个单词都变成了一个单独的选项。 如果有人能告诉我我做错了什么,我将不胜感激?

你们非常亲密!

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

应该是

combobox_values = my_dict.keys()

通过使用 join,您可以从字典中取出所有键,然后将它们放入一个字符串中!当 Tkinter 尝试描述您的字符串时,它认为空格与用于分解项目的换行符一样好。


实际追踪引擎盖下使用的描述有点棘手。 The official docs don't mention

检查源代码 Combobox 继承自 Entry 小部件,但两者都对底层 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,ttk 采取的 fail-slow 方法似乎是合适的……但它没有回答问题……

事实上,这是一个有趣的游戏:尝试破坏构造函数。传递一个随机数?以下全部工作

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

经过进一步调查,最终的 python 调用发生在 Tkinter.py 的第 2058 行(左右,取决于实现)。如果你真的很好奇,你可以从 tcl docs into their detailed widgets section,特别是章节 "Keeping Extra Item Data" 开始,看看这些事情是如何以及为什么会像他们那样发生的

在后两者中,显示方法清楚地表明,输入被包装为它自己的字符串表示形式(与新墨西哥州的解释保持一致),但底层方法仍然是回避的