Tk treeview column sort

后端 未结 5 2091
旧巷少年郎
旧巷少年郎 2020-11-30 05:26

Is there a way to sort the entries in a Tk Treeview by clicking the column? Surprisingly, I could not find any documentation/tutorial for this.

5条回答
  •  误落风尘
    2020-11-30 05:39

    make this small change to the function if you have integers in your table it will look like this.

    def treeview_sort_column(treeview: ttk.Treeview, col, reverse: bool):
        """
        to sort the table by column when clicking in column
        """
        try:
            data_list = [
                (int(treeview.set(k, col)), k) for k in treeview.get_children("")
            ]
        except Exception:
            data_list = [(treeview.set(k, col), k) for k in treeview.get_children("")]
    
        data_list.sort(reverse=reverse)
    
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(data_list):
            treeview.move(k, "", index)
    
        # reverse sort next time
        treeview.heading(
            column=col,
            text=col,
            command=lambda _col=col: treeview_sort_column(
                treeview, _col, not reverse
            ),
        )
    
    

提交回复
热议问题