Intercept event when combobox edited

Matt Fenwick picture Matt Fenwick · Dec 8, 2011 · Viewed 11.8k times · Source

I'm using a ComboBox as part of a larger GUI, written in python/tkinter.

When the drop-down selection is changed, the color is updated to indicate to the user that something has changed.

However, the combobox also allows the user to type in their own value. I also want the color to change when this happens.

The problem is, I don't see anything in the ComboBox documentation indicating how to do this.

Answer

FabienAndre picture FabienAndre · Dec 8, 2011

You can use a StringVar as a parameter of the Combobox constructor. This StringVar can be traced (ie, subscribe to each change).

Here a small example:

from Tkinter import *
from ttk import *

def on_field_change(index, value, op):
    print "combobox updated to ", c.get()

root = Tk()
v = StringVar()
v.trace('w',on_field_change)
c = Combobox(root, textvar=v, values=["foo", "bar", "baz"])
c.pack()

mainloop()