How to make a ttk.Combobox callback

Marek picture Marek · Feb 4, 2016 · Viewed 14.7k times · Source

I was wondering if there was a way to invoke a call back from a ttk.Combobox when the user selects an item from the drop-down list. I want to check to see what the value of the combobox is when an item is clicked so that I can display the associated dictionary value given the combobox key.

import Tkinter
import ttk

FriendMap = {}
UI = Tkinter.Tk()
UI.geometry("%dx%d+%d+%d" % (330, 80, 500, 450))
UI.title("User Friend List Lookup")

def TextBoxUpdate():
    if not  FriendListComboBox.get() == "":
        FriendList = FriendMap[FriendListComboBox.get()]
        FriendListBox.insert(0,FriendMap[FriendListComboBox.get()])`

#Imports the data from the FriendList.txt file
with open("C:\Users\me\Documents\PythonTest\FriendList.txt", "r+") as file:
for line in file:
    items = line.rstrip().lower().split(":")
    FriendMap[items[0]] = items[1]

#Creates a dropdown box with all of the keys in the FriendList file
FriendListKeys = FriendMap.keys()
FriendListKeys.sort()
FriendListComboBox = ttk.Combobox(UI,values=FriendListKeys,command=TextBoxUpdate)`

The last line obviously doesn't work since there is no 'command' for Comboboxes but I am not really sure what I need to do here to get that to work. Any help would be appreciated.

Answer

Bryan Oakley picture Bryan Oakley · Feb 4, 2016

You can bind to the <<ComboboxSelected>> event which will fire whenever the value of the combobox changes.

def TextBoxUpdate(event):
    ...
FriendListComboBox.bind("<<ComboboxSelected>>", TextBoxUpdate)