2

Is there a way with pysimplegui to sort a table by columns? I looked around on github for some examples but couldn't find anything.

I found this example that creates a table from a csv file:

#!/usr/bin/env python
import PySimpleGUI as sg
import csv

# Show CSV data in Table
sg.theme('Dark Red')

def table_example():
    filename = sg.popup_get_file('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
    # --- populate table with file contents --- #
    if filename == '':
        return
    data = []
    header_list = []
    button = sg.popup_yes_no('Does this file have column names already?')
    if filename is not None:
        with open(filename, "r") as infile:
            reader = csv.reader(infile)
            if button == 'Yes':
                header_list = next(reader)
            try:
                data = list(reader)  # read everything else into a list of rows
                if button == 'No':
                    header_list = ['column' + str(x) for x in range(len(data[0]))]
            except:
                sg.popup_error('Error reading file')
                return
    sg.set_options(element_padding=(0, 0))

    layout = [[sg.Table(values=data,
                            headings=header_list,
                            max_col_width=25,
                            auto_size_columns=True,
                            justification='right',
                            # alternating_row_color='lightblue',
                            num_rows=min(len(data), 20))]]


    window = sg.Window('Table', layout, grab_anywhere=False)
    event, values = window.read()

    window.close()

table_example()

I am pretty new to python and pysimplegui so sorry in advance if this questions has been asked already (I looked around on this site but couldn't find anything related).

ragnoki
  • 23
  • 4
  • Just replied in https://stackoverflow.com/questions/68999955/sorting-table-by-columns/69001759#69001759 – Jason Yang Sep 01 '21 at 13:04
  • Thanks. Yea I saw that post, your answer is a good first step but then I am still having issues sorting the table …(answer only shows how to select a column) – ragnoki Sep 01 '21 at 13:41
  • You can sort data by `data = sorted(data, key=key, reverse=reverse)`, then update your table by `table.update(values=data)` – Jason Yang Sep 01 '21 at 13:52

1 Answers1

0

There's a demo program and an eCookbook page specifically to demonstrate how to sort by columns.

enter image description here

enter image description here

The eCookbook (Trinket) link is here: https://pysimplegui.trinket.io/demo-programs#/tables/table-element-getting-click-events

This is the program I start with anytime I'm writing a PySimpleGUI program that's going to use Tables that I know will need to be sorted.

Another demo, Demo_Table_CSV_Display.pyw also has code to show you how to sort columns.

Mike from PSG
  • 5,312
  • 21
  • 39