【问题标题】:Sorting entries in a ttk treeview automaticly after inserting插入后自动对 ttk 树视图中的条目进行排序
【发布时间】:2017-10-16 09:28:22
【问题描述】:

有没有办法在不按标题的情况下达到与这篇文章 python ttk treeview sort numbers 类似的结果?最好的方法是在插入项目之后。

【问题讨论】:

    标签: python-3.x treeview ttk


    【解决方案1】:

    如果您要在每次插入新项目时对内容进行排序,那么更有效的方法是将项目插入正确的位置,而不是为每次插入对整个数据进行排序。

    这是使用标准bisect 模块实现此目的的一种方法,其bisect(a, x) 函数为您提供x 应插入a 以保持顺序的索引(假设a 已排序)。在下面的示例中:

    • 我的整个界面存储在某个类GUI
    • 我的树视图名为 self.tree,只有一列;
    • 我的insert_item 方法在树中的某个类别下方插入一个新行(由location 指向),并且每个类别下的项目必须在我的应用程序中单独排序,这就是为什么我只检索该类别的孩子.
        from bisect import bisect
    
        # ... class GUI contains the treeview self.tree ...
    
        def insert_item(self, location, item_name, item_id):
            """Inserts a new item below the provided location in the treeview,  
            maintaining lexicographic order wrt names."""
            contents = [
                self.tree.item(child)["text"]
                for child in self.tree.get_children(location)
            ]
            self.tree.insert(
                location, bisect(contents, item_name), item_id, text=item_name
            )
    

    【讨论】:

      【解决方案2】:

      要在每次插入新项目后对 Treeview 进行排序,只需在代码中的正确位置添加对排序函数的显式调用即可。

      示例代码:

      import tkinter as tk
      from tkinter import ttk
      
      counter = 0
      numbers = ['1', '10', '11', '2', '3', '4', '24', '12', '5']
      
      def sort_treeview():
          content = [(tv.set(child, column), child) 
                                      for child in tv.get_children('')]
          try:
              content.sort(key=lambda t: int(t[0]))
          except:
              content.sort()
          for index, (val, child) in enumerate(content):
              tv.move(child, '', index)
      
      def add_item():
          global counter
          if counter < 8:
              tv.insert('', 'end', values=numbers[counter])
              counter += 1
              # Sort the treeview after the new item was inserted
              # -------------------------------------------------
              sort_treeview()
      
      root = tk.Tk()
      column = 'number'
      tv = ttk.Treeview(root, columns=column, show='headings')
      tv.pack()
      
      button = tk.Button(root, text='Add entry', command=add_item)
      button.pack()
      
      root.mainloop()
      

      【讨论】:

        猜你喜欢
        • 2020-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 1970-01-01
        • 1970-01-01
        • 2017-03-06
        • 2017-02-06
        相关资源
        最近更新 更多