【问题标题】:searching in treeview with scrolling通过滚动在树视图中搜索
【发布时间】:2019-07-18 03:21:23
【问题描述】:

我正在尝试在 ttk.treeview 表中实现搜索。显然已经有一些答案,我正在使用其中一个(参见下面的代码)。但是我想扩展这个问题。

鉴于下面的代码,如何使它除了突出显示所需的元素外,视图还将滚动到该元素?
换句话说,如果列表中有更多适合视图的元素,而我们正在搜索的元素位于底部,如何将其放在视图的中间(或者顶部会更好?)在向搜索字段输入字符的过程中? 此外,由于可以一次突出显示多个元素,我想我们应该滚动到第一个元素。

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

【问题讨论】:

  • 一个解决方案是,计算第一个突出显示的行相对于scrollregion 的行位置并使用self.tree.yview_moveto(<relative pos>)

标签: python search tkinter scroll treeview


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我发现了一个技巧,可以将我感兴趣的行带到窗口顶部。先翻到底,再往上翻。

    tree.see(items[-1])
    tree.see(items[my_target_item_n])
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多