Skip to content Skip to sidebar Skip to footer

Sorting Items In Treeview After Adding Tkinter

I've got a question about alphabetically sorting rows after inserting them to tree. I tried to add method data.sort() by adding or sorted(data) but it didnt work. Or is there any w

Solution 1:

Sorting a treeview is done the following way:

  1. Collect the data from all the rows in a list.
  2. Sort the list.
  3. Move the items in the treeview to be in the same order as in the list.

Adapting the code from the answers of python ttk treeview sort numbers, this gives:

def sort():
    rows = [(tree.item(item, 'values'), item) for item in tree.get_children('')]
    # if you want to sort according to a single column:# rows = [(tree.set(item, column), item) for item in tree.get_children('')]
    rows.sort()

    # rearrange items in sorted positionsforindex, (values, item) in enumerate(rows):
        tree.move(item, '', index)

Just use the sort() function as a button's command to sort the treeview.

Edit: To sort alphabetically rows according to the value in column 'two' and regardless of capitalization:

def sort():
    rows = [(tree.set(item, 'two').lower(), item) for item in tree.get_children('')]
    rows.sort()

    for index, (values, item) in enumerate(rows):
        tree.move(item, '', index)

Post a Comment for "Sorting Items In Treeview After Adding Tkinter"