PySimpleGUI disabled an InputText according to sg.Radio?

21 Views Asked by At

I'm new to PySimpleGUI,

I want to implement this functionality: There are two radio buttons. When I select one of them, the text input box below becomes editable. When I select the other one, the text box below becomes uneditable. This is my code. I've tried many times, but I can't achieve the dynamic effect I want. Could you guys help me?

import PySimpleGUI as sg
import os as os


def main():

    sg.theme('Tan')
    column =[
        [sg.Text('sliding window?',font=('Microsoft Yahei',10)),sg.Radio('Yes','g',default=True,key='-Radio1-'),sg.Radio('No','g',default=False,key='-Radio2-')],
        [sg.Text('fill in',font=('Microsoft Yahei',10)),sg.InputText('3',key='-S_Window-',visible=True,disabled=False, enable_events=True)],
        ] 
    layout = [[sg.Column(column)]]
    
    # Create the window
    window = sg.Window('abcd', layout,resizable='True',finalize=True)


    while True:
        event, values = window.read()
        if values['-Radio1-'] == True:
            window['-S_Window-'].update(disabled=False)
            window.refresh()
        if values['-Radio2-'] == True:
            window['-S_Window-'].update(disabled=True,background_color = 'grey')
            window.refresh()

    window.close()

if __name__ =='__main__':
        main()

enter image description here

1

There are 1 best solutions below

1
Jason Yang On

With option enable_events=True in your sg.Radio elements to generate event when clicked, or it won't generate event when you click on them and no update for disabled state of the Input element.

import PySimpleGUI as sg

sg.theme('DarkBlue')
layout =[
    [sg.Radio('Yes', 'g', enable_events=True, key=("Radio", 1)),
     sg.Radio('No',  'g', enable_events=True, key=("Radio", 2))],
    [sg.InputText('3', enable_events=True, key='-S_Window-')],
]
window = sg.Window('Title', layout)

while True:

    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break
    elif isinstance(event, tuple) and event[0] == "Radio":
        disabled = (event[1]==2)
        window['-S_Window-'].update(disabled=disabled)

window.close()