[英]How to make a ttk.Combobox callback
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. 当用户从下拉列表中选择一个项目时,我想知道是否有办法从ttk.Combobox调用回调。 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. 最后一行显然不起作用,因为Comboboxes没有“命令”,但我不确定我需要做什么才能让它工作。 Any help would be appreciated.
任何帮助,将不胜感激。
You can bind to the <<ComboboxSelected>>
event which will fire whenever the value of the combobox changes. 您可以绑定到
<<ComboboxSelected>>
事件,只要组合框的值发生变化,该事件就会触发。
def TextBoxUpdate(event):
...
FriendListComboBox.bind("<<ComboboxSelected>>", TextBoxUpdate)
Use IntVar and StringVar . 使用IntVar和StringVar 。
You can use the trace method to attach “observer” callbacks to the variable.
您可以使用trace方法将“observer”回调附加到变量。 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)`
the callback function will be called when the comobox changes 当comobox更改时,将调用回调函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.