如何添加新选项,然后在 python tkinter optionMenu 中读取新选择的选项?

How do I add new options, and then read the new selected option in a python tkinter optionMenu?

使用我目前拥有的代码,当程序启动时,我可以 select 从 3 个选项中选择,并将该选项打印到控制台。我还可以将文本输入到文本条目中,通过按下按钮将其添加到选项菜单列表中。

通过添加新选项,它破坏了 optionMenu,我无法再从 optionMenu 中获得 selected 选项。

我已尝试查看 tkinter 文档(我能找到的那一点),但没有找到与我的问题相关的信息。

import tkinter

category_list = ['Option A', 'Option B','Option C']

def add_To_List():
    entry = entry_Right.get()
    if entry not in category_list:
        option_Left_StringVar.set('')

        menu_left = option_Left["menu"]
        menu_left.delete(0, "end")
        category_list.append(entry)

        for choice in category_list:
            menu_left.add_command(label=choice, 
command=tkinter._setit(option_Left_StringVar, choice))

def option_Left_Function(selection):
    print(selection)

#----GUI----

root = tkinter.Tk()

frame_Left = tkinter.Frame(root)
frame_Left.grid(column=0, row=0, sticky='w')


option_Left_StringVar = tkinter.StringVar(frame_Left)
option_Left = tkinter.OptionMenu(frame_Left, option_Left_StringVar, 
*category_list, command=option_Left_Function)
option_Left.grid(column=0, row=0, sticky='w')


frame_Right = tkinter.Frame(root)
frame_Right.grid(column=1, row=0, sticky='e')

entry_Right = tkinter.Entry(frame_Right)
entry_Right.grid(column=1, row=0, sticky='w')

button_Right = tkinter.Button(frame_Right, text='Add to list', 
command=add_To_List)
button_Right.grid(column=2, row=0, sticky='w')

root.mainloop()

我能做的最远的事情(如您在上面的代码中所见)是向 optionMenu 添加一个新选项,但是当我无法访问 selection 时这无济于事代码中的 optionMenu。

在此问题上,我非常感谢您的帮助,谢谢。

您必须添加 option_Left_Function 作为第三个参数

command=tkinter._setit(option_Left_StringVar, choice, option_Left_Function)

使用 print(tkinter.__file__) 你可以获得源代码的路径,你可以在这个文件中看到它。


顺便说一句:您不必删除旧项目。您只能添加新项目。

def add_To_List():
    entry = entry_Right.get()
    if entry not in category_list:
        option_Left_StringVar.set('')

        menu_left = option_Left["menu"]
        menu_left.add_command(label=entry, 
                  command=tkinter._setit(option_Left_StringVar, entry, option_Left_Function))

        category_list.append(entry)