0

In the example below the variable 'food' gets printed when the button OK is clicked. I need to eliminate this OK button, therefor I would like the 'food' variable to be printed upon selecting it in the drop down menu. Can someone show me how I can get this result please? Please make the answer clear and simple since I am a beginner with tkinter.

from Tkinter import *
import ttk

Root = Tk()

var = StringVar(Root)
var.set("apple") # initial value

option = ttk.Combobox(Root, textvariable=var, values=["apple", "carrot", "orange"])
option.pack()

def ok():
    food = var.get()
    print(food)

button = Button(Root, text="OK", command=ok)
button.pack()

mainloop()
julie
  • 1

2 Answers2

1

You can bind functions to events, so that the function is called when the event happens for the widget. In the case of a combobox, you can bind to the <<ComboboxSelected>> event. When the value changes, this event is generated for the combobox, and it will cause your function to be called.

Note: when you bind to events, the function that is called will be given an object that represents the event. If you want to use the function both with and without using bind you can make the event object optional by assigning it a default value of None.

Here is an example:

def ok(event=None):
    food = var.get()
    print(food)

option.bind("<<ComboboxSelected>>", ok)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
-1

Try looking at this link : How do you run your own code alongside Tkinter's event loop?

You will need to call your ok function repeatedly using the after method of the Root object.

delay = 20 #milliseconds

def ok():
    food = var.get()
    print(food)
    Root.after(20, ok) #Will call itself after every 20 ms

Root.after(20,ok) #This is for the first call from the root to enter the ok function

Root.mainloop()
Community
  • 1
  • 1
  • Why do you need to use `after`? The user isn't asking how to continually run the function, they simply want to run the function when the value changes. – Bryan Oakley Aug 08 '15 at 11:44
  • I agree your method is better, but this code solves the problem too. The after method forces the ok function acts like a continues listener to any event triggered in the comboBox. It also does not affect other events happening in the root. You can add some other functionality to the button and see that it works even while the ok function is being called repeatedly. All said, your solution is the right one. – Addarsh Chandrasekar Aug 08 '15 at 16:36
  • I don't think your code solves the problem at all. It causes printing to happen 50 times per second whether the value changes or not, but the OP wants the print to happen exactly once each time the value changes. This answer solves a different problem than the one that was asked. – Bryan Oakley Aug 08 '15 at 18:12
  • If it has to be printed exactly once, then yes, my code doesn't solve the problem. Thanks for pointing it out. – Addarsh Chandrasekar Aug 08 '15 at 18:31