如何进行 ttk.Combobox 回调

How to make a ttk.Combobox callback

我想知道是否有一种方法可以在用户从下拉列表中选择一个项目时从 ttk.Combobox 调用回调。我想查看单击某个项目时组合框的值是什么,以便我可以在给定组合框键的情况下显示关联的字典值。

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)`

最后一行显然不起作用,因为组合框没有 'command',但我不太确定我需要在这里做什么才能让它起作用。任何帮助将不胜感激。

使用IntVar and StringVar.

You can use the trace method to attach “observer” callbacks to the variable. The callback is called whenever the contents change:

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[UserListComboBox.get()])`
def calback():
    print("do something")

#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
value = StringVar()
value.trace('w', calback)
FriendListKeys = FriendMap.keys()
FriendListKeys.sort()
FriendListComboBox =   ttk.Combobox(UI,values=FriendListKeys,command=TextBoxUpdate,textvariable=value)`

组合框变化时会调用回调函数

您可以绑定到 <<ComboboxSelected>> 事件,只要组合框的值发生变化,该事件就会触发。

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