python-3.xpysimplegui

Update a checkbox based on selected values of another checkbox


I want to have a select all checkbox in my PySimpleGUI. When the select all checkbox is selected, all other checkboxes should change to True, and if any other box is unchecked, the select all checkbox should change to false state?

I can do it through button clicks, but I couldn't find a way to update checkboxes based on values selected in an another checkbox?

import PySimpleGUI as sg
layout = [
    [sg.Checkbox ('select all', key = 'checkbox')],
    [sg.Checkbox ('value 1', key='check_value1')],
    [sg.Checkbox ('value 2',key='check_value2')],
    [sg.Button ('ON', key = 'ON')],
    [sg.Button ('OFF', key = 'OFF')]
]
window = sg.Window ('Sample GUI', layout) .Finalize ()
while True: # Event Loop
    event,values=window.read()
    if event in (None, 'Exit'):
        break
    elif event == 'ON':
        window ['checkbox']. Update (value = True)
    elif event == 'OFF':
        window ['checkbox']. Update (value = False)
    print(event,values)
window.close ()

Is there any way to implement this?


Solution

  • Option value or first argument in method update if True checks the checkbox, False clears it,

    Demo code,

    enter image description here

    import PySimpleGUI as sg
    
    sg.theme('DarkBlue')
    
    layout = [
        [sg.Checkbox('All checked',   enable_events=True, key='Check_All'),
         sg.Checkbox('All unchecked', enable_events=True, key='Uncheck_All')],
        [sg.HorizontalSeparator()]] + [
        [sg.Checkbox(f'check ({j}, {i})', enable_events=True, key=f'check{j}{i}')
            for i in range(5)] for j in range(4)
    ]
    
    window = sg.Window ('Sample GUI', layout, finalize=True)
    
    while True: # Event Loop
        event, values = window.read (timeout = 100)
        if event == sg.WINDOW_CLOSED:
            break
        elif event == 'Check_All':
            for j in range(4):
                for i in range(5):
                    window[f'check{j}{i}'].update(True)
            window['Uncheck_All'].update(False)
        elif event == 'Uncheck_All':
            for j in range(4):
                for i in range(5):
                    window[f'check{j}{i}'].update(False)
            window['Check_All'].update(False)
        elif event.startswith('check'):
            if not values[event]:
                window['Check_All'].update(False)
            else:
                window['Uncheck_All'].update(False)
    
    window.close ()