ragardner / tksheet

Python tkinter table widget for displaying tabular data
https://pypi.org/project/tksheet/
MIT License
408 stars 50 forks source link

Rows sorting? #218

Closed majki09 closed 7 months ago

majki09 commented 7 months ago

How do I sort rows with some column?

ragardner commented 7 months ago

Hello,

There is currently no in-built way to do this, it would require getting the table and index data which is a list of lists, the sublists are rows, sorting this and then setting the table and index data to the newly sorted data

Once you have the data from the table a basic way of sorting the list of lists by a column would be something like this: https://stackoverflow.com/a/4174955/7655687

There are more advanced methods which take into account digits utilising the sort() methods key= parameter

For example:

def sort():
    col = 1
    sort_key = lambda row: [
            int(c) if c.isdigit() else c.lower() for c in re.split("([0-9]+)", f"{row[col]}")
        ]
    span = sheet[:].options(index=True)
    sheet.set_data(span, data=sorted(span.data, key=sort_key))

You will have to research what key you want to use as I am not experienced with sorting, natural sorting etc.

There are some libraries which handle it pretty well, for example: https://github.com/SethMMorton/natsort

I hope this helps!

majki09 commented 7 months ago

Is it that simple? Thank you so much for the answer and all your effort for tksheet 😀