Adding command to a Tkinter OptionMenu?

27,405

There is never a need for a direct apply call, which is why is is dreprecated in 2.7 and gone in 3.0. Instead use the *seq syntax. Just combine the two things you did. The following seems to do what you want.

from tkinter import *

def func(value):
    print(value)

root = Tk()
options = ["1", "2", "3"]
var = StringVar()
drop = OptionMenu(root, var, *options, command=func)
drop.place(x=10, y=10)
Share:
27,405
Paul McDonald
Author by

Paul McDonald

Updated on August 14, 2020

Comments

  • Paul McDonald
    Paul McDonald almost 4 years

    I'm writing some code in Python 2.7.8 which includes the OptionMenu widget. I would like to create an OptionMenu that calls a function when the option is changed but I also want the possible options to be found in a list, as my final OptionMenu will have many options.

    I have used the following code to create an OptionMenu that calls a function:

    from Tkinter import*
    
    def func(value):
        print(value)
    
    root = Tk()
    
    var = StringVar()
    DropDownMenu=OptionMenu(root, var, "1", "2", "3", command=func)
    DropDownMenu.place(x=10, y=10)
    
    root.mainloop()
    

    I have also found the following code that creates an OptionMenu with options found in a list:

    from Tkinter import*
    
    root = Tk()
    
    Options=["1", "2", "3"]
    var = StringVar()
    DropDownMenu=apply(OptionMenu, (root, var) + tuple(Options))
    DropDownMenu.place(x=10, y=10)
    
    root.mainloop()
    

    How would I create an OptionMenu that calls a function when the option is changed and gets the possible options from a list?

  • martineau
    martineau almost 7 years
    apply() has been deprecated since version 2.3 (according to the current 2.7 documentation.