Search code examples
python-3.xtreeviewttk

Sorting entries in a ttk treeview automaticly after inserting


Is there a way to achieve a similar result like in this post python ttk treeview sort numbers but without pressing on the heading? Best way would be right after an item is inserted.


Solution

  • If you are going to sort your contents every time you insert a new item, then a more efficient approach would be to insert the item in the right place rather than sorting the whole data for each insertion.

    Here's one way to achieve this using the standard bisect module, whose bisect(a, x) function gives you the index at which x should be inserted in a to maintain order (a is assumed to be sorted). In my example below:

    • my whole interface is stored in some class GUI;
    • my treeview is called self.tree and features only one column;
    • my insert_item method inserts a new line below a certain category in the tree (pointed to by location), and items below each category must be sorted separately in my application, which is why I only retrieve that category's children .
        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
            )