【问题标题】:How do I add new options, and then read the new selected option in a python tkinter optionMenu?如何添加新选项,然后在 python tkinter optionMenu 中读取新选择的选项?
【发布时间】:2019-11-07 11:55:24
【问题描述】:

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

通过添加新选项,它会破坏 optionMenu,并且我不再能够从 optionMenu 中获取所选选项。

我已尝试查看 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 添加一个新选项,但是当我无法在代码中访问 optionMenu 的选择时,这无济于事。

非常感谢您在这个问题上的帮助,谢谢。

【问题讨论】:

    标签: python tkinter insert options tkinter.optionmenu


    【解决方案1】:

    您必须添加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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      相关资源
      最近更新 更多