PySimpleGUI Change Table row color based on value (substring) condition

374 Views Asked by At

I have been using PySimpleGUI and am trying to apply the following function: I am trying to work out how to change individual row colors (and/or change those row text colours) of an "updating" table based on a substring present in a column. For example with this sample code from https://www.tutorialspoint.com/pysimplegui/pysimplegui_table_element.htm, if I wanted the row color to change to green if substring "Ra" is present in column 1, is it possible? I think I would need to insert this code:

window['-TABLE-'].Update(row_colors=[[ROW TO CHANGE,'green']]) 

but do not know how to have a substring search on each row of a particular column as an event and to then apply that code to the appropriate row. Thanks

import PySimpleGUI as psg
psg.set_options(font=("Arial Bold", 14))
toprow = ['S.No.', 'Name', 'Age', 'Marks']
rows = [[1, 'Rajeev', 23, 78],
        [2, 'Rajani', 21, 66],
        [3, 'Rahul', 22, 60],
        [4, 'Robin', 20, 75]]
tbl1 = psg.Table(values=rows, headings=toprow,
   auto_size_columns=True,
   display_row_numbers=False,
   justification='center', key='-TABLE-',
   selected_row_colors='red on yellow',
   enable_events=True,
   expand_x=True,
   expand_y=True,
 enable_click_events=True)
layout = [[tbl1]]
window = psg.Window("Table Demo", layout, size=(715, 200), resizable=True)
while True:
   event, values = window.read()
   print("event:", event, "values:", values)
   if event == psg.WIN_CLOSED:
      break
   if '+CLICKED+' in event:
      psg.popup("You clicked row:{} Column: {}".format(event[2][0], event[2][1]))
window.close()
1

There are 1 best solutions below

0
On BEST ANSWER

Check the value of column 1 for each row if it contain the substring "Ra", then call method update of Table element to update the colors.

row_colors

list of tuples of (row, background color) OR (row, foreground color, background color). Changes the colors of listed rows to the color(s) provided (note the optional foreground color)

Reduced code

import PySimpleGUI as sg

headings = ['S.No.', 'Name', 'Age', 'Marks']
rows = [
    [1, 'Rajeev', 23, 78],
    [2, 'Rajani', 21, 66],
    [3, 'Rahul', 22, 60],
    [4, 'Robin', 20, 75],
]

table = sg.Table(
    values=rows,
    headings=headings,
    justification='center',
    selected_row_colors='red on yellow',
)
layout = [[table], [sg.Push(), sg.Button("Check")]]
window = sg.Window("Table Demo", layout)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    elif event == "Check":
        row_colors = [(i, "white", "blue") for i, row in enumerate(rows) if "Ra" in row[1]]
        table.update(row_colors=row_colors)

window.close()

enter image description here