请在下面查看我的解释性代码段:
from tkinter import *from tkinter import ttkclass App: def __init__(self, root): self.root = root self.tree = ttk.Treeview(self.root) #create tree self.sv = StringVar() #create stringvar for entry widget self.sv.trace("w", self.command) #callback if stringvar is updated self.entry = Entry(self.root, textvariable=self.sv) #create entry self.names = ["Jane", "Janet", "James", "Jamie"] #these are just test inputs for the tree self.ids = [] #creates a list to store the ids of each entry in the tree for i in range(len(self.names)): #creates an entry in the tree for each element of the list #then stores the id of the tree in the self.ids list self.ids.append(self.tree.insert("", "end", text=self.names[i])) self.tree.pack() self.entry.pack() def command(self, *args): self.selections = [] #list of ids of matching tree entries for i in range(len(self.names)): #the below if check checks if the value of the entry matches the first characters of each element #in the names list up to the length of the value of the entry widget if self.entry.get() != "" and self.entry.get() == self.names[i][:len(self.entry.get())]: self.selections.append(self.ids[i]) #if it matches it appends the id to the selections list self.tree.selection_set(self.selections) #we then select every id in the listroot = Tk()App(root)root.mainloop()
因此,每次
entry更新窗口小部件时,我们都会循环浏览名称列表,并检查
entry窗口小部件的值是否与
elementin中的值匹配,
names
list直到不超过窗口小部件的值的长度
entry(例如,如果输入5个字符长的字符串,然后我们对照该元素的前5个字符进行检查)。
如果它们匹配
id,则将树条目的附加到
list。
检查完所有名称后,我们将
list匹配
id的传递给
self.tree.selection_set(),然后突出显示所有匹配的树条目。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)