OptionMenu add_command是否需要直接命令?

问题描述 投票:0回答:1

我被卡住了

我正在使用refresh()函数更改OptionMenu的内容,在情况A中它可以正常工作,但是在情况B中,如果我将其更改为回调,则OptionMenu停止工作。单击选项不再选择它。

任何想法使它如此吗?

案例A:

import tkinter as tk
root = tk.Tk()
cvar = tk.StringVar(root)
cvar.set("-")
optionlist = ('one', 'two', 'three')

def refresh(contentlist):
    optionmenu['menu'].delete(0, 'end')

    for content in contentlist:
        optionmenu['menu'].add_command(label=content, command=tk._setit(cvar, content))

def doNothing():
    return

optionmenu = tk.OptionMenu(root, cvar, *optionlist, command=doNothing)
optionmenu.pack()

refresh(optionlist)

root.mainloop()

情况B:

def contentcallback(var, name):
    tk._setit(var, name)

def refresh(contentlist):
    optionmenu['menu'].delete(0, 'end')

    for content in contentlist:
        optionmenu['menu'].add_command(label=content, command=contentcallback(cvar, content))
python python-3.x tkinter optionmenu tkinter.optionmenu
1个回答
0
投票

@ stovfl发表评论,给了我另一个解决方案

tk._setit具有我不知道的回调函数。使用该回调,我可以做到:

def contentcallback(var, name):
    #Whatever I need to do

def refresh(contentlist):
    optionmenu['menu'].delete(0, 'end')

    for content in contentlist:
        optionmenu['menu'].add_command(label=content, command=tk._setit(var, name, lambda cv=cvar, con=content: contentcallback(cv, con)))
© www.soinside.com 2019 - 2024. All rights reserved.