Python 通过滚动在treeview中搜索
我正在尝试在ttk.treeview表中实现搜索。显然已经有一些答案了,我正在使用其中的一个(见下面的代码)。不过,我想扩大问题的范围 给出下面的代码,如何使它除了突出显示所需的元素外,还可以滚动到该元素?Python 通过滚动在treeview中搜索,python,search,tkinter,scroll,treeview,Python,Search,Tkinter,Scroll,Treeview,我正在尝试在ttk.treeview表中实现搜索。显然已经有一些答案了,我正在使用其中的一个(见下面的代码)。不过,我想扩大问题的范围 给出下面的代码,如何使它除了突出显示所需的元素外,还可以滚动到该元素? 换句话说,如果列表中有更多适合视图的元素,并且我们正在搜索的元素位于底部,那么在将字符输入到搜索字段的过程中,如何将其置于视图的中间(或者顶部更好?)? 另外,由于可以同时突出显示多个元素,我想我们应该滚动到第一个元素 from tkinter import * from tkinter i
换句话说,如果列表中有更多适合视图的元素,并且我们正在搜索的元素位于底部,那么在将字符输入到搜索字段的过程中,如何将其置于视图的中间(或者顶部更好?)? 另外,由于可以同时突出显示多个元素,我想我们应该滚动到第一个元素
from tkinter import *
from tkinter import ttk
class 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 = [
"tawymu","uzzkhv","mimfms","qpugux","mswzaz","alexsa","khfpke",
"fsphkn","indzsl","rmvuag","gvrmxd","vfshxx","kwpuyz","pyfmar",
] # 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 list
root = Tk()
App(root)
root.mainloop()
对于
treeview
,有一个see
方法
def command(self, *args):
self.selections = []
for i in range(len(self.names)):
if self.entry.get() != "" and self.entry.get() == self.names[i][:len(self.entry.get())]:
self.selections.append(self.ids[i])
self.tree.selection_set(self.selections)
try:
self.tree.see(self.selections[0]) #you can iterate through the list for multiple selection
except IndexError:
pass
我找到一个黑客把我感兴趣的那一行带到了窗口的顶端。先爬到底,然后再爬起来
tree.see(items[-1])
tree.see(items[my_target_item_n])
一种解决方案是,计算第一个高亮显示行相对于
scrollregion
的行位置,并使用self.tree.yview\u moveto()
。