Search code examples
pythontkinteroptionmenu

Tkinter: How to call a function using the OptionMenu widget?


I'm working on a simple Python-Tkinter application. Here's a simplification of the code I'm having now.

from Tkinter import *
root = Tk()

def function(x): 

    if x == "yes":
        a.set("hello")
    else:
        a.set("bye")

#-----------------------------

a = StringVar()
a.set("default")

oc = StringVar(root)
oc.set("Select")
o = OptionMenu(root, oc, "yes", "no", command=function)
o.pack()

z = a.get() 
print z # prints default

root.mainloop()

I want this code to print "hello" or "bye" to the console but instead it prints "default".

I have been trying to make this work but somehow I can't figure it out. The code works fine if I call the function directly instead of using an Optionmenu widget:

z = function("yes")
print z #prints hello

or:

z = function("no") 
print z #prints bye

Could someone explain why it doesn't print "hello" or "bye" when I use the Optionmenu widget. And how do I fix it so I can use the variable z without changing the part above the line?

Thanks!


Solution

  • from Tkinter import *
    root = Tk()
    
    a = StringVar()
    a.set("default")
    
    oc = StringVar(root)
    oc.set("Select")
    
    def function(x):
    
      if x == "yes":
          a.set("hello")
          print a.get()
    
      else:
          a.set("bye")
          print a.get()
    
    o = OptionMenu(root, oc, "yes", "no", command=function)
    o.pack()
    
    
    z = a.get()    
    print z
    
    root.mainloop()
    

    OptionMenu executes function now when the OptionMenu selection is changed -- if the option menu reads "yes", function executes with "yes" as its parameter and sets a to "hello" and sets a to "bye" for all other options.