0

I am stuck

I am changing the content of an OptionMenu with the refresh() function and it works fine in case A but when in case B where I change it to a callback the OptionMenu stops working. Clicking on an option no longer selects it.

Any idea what makes it so?

Case 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()

Case 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))
XGG
  • 41
  • 5

1 Answers1

0

@stovfl made a comment that gave me another solution

tk._setit has a callback function I did not know about. Using that callback I can do:

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)))

EDIT: @BryanOakley gave a link to why my original solution was full of holes

The tk._setit method returns an object that is needed to make it work. The original contentcallback only called the method and not the one behind it. This made it a little weird to setup:

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

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

    for content in contentlist:
        optionmenu['menu'].add_command(label=content, command=lambda cv=cvar, co=content, func=tk._setit(cvar, content): contentcallback(cvar, co, func))
XGG
  • 41
  • 5