Search code examples
pythonpython-3.xtkintertreeview

Treeview Tuple Sort as String (Wrong Order)


enter image description here

Alright, after hours of fiddling around I can't seem to fix this bug. I've tried changing my types to integers, with key = operator.itemgetter(0) and I've also tried with other fix like using iteration_utilities: chained, functools --> Without success

It returns a list of tuples ex: [('27958', 'I008'), ('28497', 'I00C'), ('28652', 'I018'), ('28653', 'I001'), ('28713', 'I009'), ('29262', 'I00A'), ('29448', 'I00B'), ('9234', 'I00D'), ('9250', 'I00E')]
As you can see, the numbers starting by 9 are at the end, I'm assuming because it treats it as a string no matter what.

I'm using the basic Treeview_sort_column function often spoken about, nothing fancy.

def treeview_sort_column(t1, col, reverse):
    l = [(t1.set(k, int(col)), k) for k in t1.get_children('')]
    l.sort(reverse=reverse) 
    print(l)

    for index, (val, k) in enumerate(l):
        t1.move(k, '', index)

    t1.heading(col, command=lambda _col=col: treeview_sort_column(t1, _col, not reverse))

for col in columns:
    t1.heading(col, text=col,command=lambda _col=col: treeview_sort_column(t1, _col, False))

Solution

  • Thank you ( Just learned it ) it did solve the issue. It solved all my issues instantly and with simplicity... much easier than all I've tried!

    For those looking for the solution

    l.sort(key=lambda t: int(t[0]), reverse=reverse)