Getting the choice of optionmenu right after selection Python

user3404844 picture user3404844 · Mar 17, 2014 · Viewed 15.1k times · Source

I was wondering if there is any way for me to see what the User has selected among the list displaying, let's say: ["Apple","Orange","Grapes"] right after they select either one of them?

Like when user clicks the optionbox, and clicks Apple, Tkinter will return something

then if he switches his selection to, let's say, Orange, then that will also return something on the spot.

Thanks!


How to put parameter correctly?

from Tkinter import *

def option_changed(a):
    print "the user chose the value {}".format(variable.get())
    print a

master = Tk()

a = "Foo"
variable = StringVar(master)
variable.set("Apple") # default value
variable.trace("w", option_changed(a))

w = OptionMenu(master, variable, "Apple", "Orange", "Grapes")
w.pack()

mainloop()

Answer

Kevin picture Kevin · Mar 17, 2014

Trace the StringVar.

from Tkinter import *

def option_changed(*args):
    print "the user chose the value {}".format(variable.get())
    print a

master = Tk()

a = "Foo"
variable = StringVar(master)
variable.set("Apple") # default value
variable.trace("w", option_changed)

w = OptionMenu(master, variable, "Apple", "Orange", "Grapes")
w.pack()

mainloop()

Here, option_changed will be called whenever the user chooses an option from the option menu.


You can wrap the trace argument in a lambda to specify your own parameters.

def option_changed(foo, bar, baz):
    #do stuff

#...
variable.trace("w", lambda *args: option_changed(qux, 23, "hello"))