簡體   English   中英

如何制作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)`

最后一行顯然不起作用,因為Comboboxes沒有“命令”,但我不確定我需要做什么才能讓它工作。 任何幫助,將不勝感激。

您可以綁定到<<ComboboxSelected>>事件,只要組合框的值發生變化,該事件就會觸發。

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

使用IntVarStringVar

您可以使用trace方法將“observer”回調附加到變量。 只要內容發生變化,就會調用回調:

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

當comobox更改時,將調用回調函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM