kenos_x
kenos_x

Reputation: 41

Sorting Tkinter Treeview columns with different types

I have recently added both coordinates and dates to my treeview in Tkinter and my sort is now failing when trying to sort both the reals in the coordinate columns and the dates in the date column.

My previous sort function is below and was designed specifically with text and integers in mind but I now need to upgrade it. I did have a look at another post that uses an upgrade of the treeview class but I'd prefer to keep this portion of the code procedural, as opposed to OOP, if at all possible.

    def treeviewSort(treeview, column, reverse: bool):
    try:
        dataList = [
            (int(treeview.set(k, column)), k) for k in
            treeview.get_children("")
        ]
    except Exception:
        dataList = [(treeview.set(k, column), k) for k in
                    treeview.get_children("")]

    dataList.sort(reverse=reverse)

    for index, (val, k) in enumerate(dataList):
        treeview.move(k, "", index)

    treeview.heading(
        column=column,
        text=column.title(),
        command=lambda _col=column: treeviewSort(
            treeview, _col, not reverse
        ),
    )

columns = ("species", "location", "x", "y", "time",
           "date", "temperature", "humidity", "user", "#")
table = ttk.Treeview(frame, columns=columns, show="headings",
                     height=30)
for col in columns:
    table.heading(col, text=col,
                  command=lambda _col=col: treeviewSort(table, _col,
                                                        False))

For reference:

I figure the solution is to add a checker in my function which checks the column type and sorts accordingly but I am unsure how to implement this.

Upvotes: 0

Views: 849

Answers (1)

kenos_x
kenos_x

Reputation: 41

Fixed this by adding if statements based on the column selected as I had guessed. Only just worked out how to do it though.

If the data is in the x or y columns it turns the data to float to then sort. If in the date column, it uses datetime.strptime to then sort by date. Otherwise, it runs as per normal. The code is below in case it helps anyone.

    if column == "x" or column == "y":
        dataList.sort(reverse=reverse, key=lambda t: (float(t[0])))
    elif column == "date":
        dataList.sort(reverse=reverse,
                      key=lambda t: datetime.strptime(t[0], "%d/%m/%Y"))
    else:
        dataList.sort(reverse=reverse)

Upvotes: 1

Related Questions