How to toggle visibility of a Gradio component based on radio button?

314 Views Asked by At

I am trying to toggle the visibility of a Gradio component based on values selected through a radio button.

import gradio as gr

with gr.Blocks() as demo:

    radio = gr.Radio(["show", "hide"], label="Choose")
    text = gr.Textbox(label="This text only shows when 'show' is selected.", visible=False)

    
    def update_visibility(radio, text):  # Accept the event argument, even if not used
        value = radio  # Get the selected value from the radio button
        if value == "show":
            text.visible = True
        else:
            text.visible = False
    radio.change(update_visibility, [radio, text], text)

demo.launch()

The code I am trying, looks something like this. However, it leads to an error like this:

AttributeError: 'str' object has no attribute 'visible' 

I understand the error. Isin't there any way by which I can pass the actual component to the event handler instead of the value they represent?

1

There are 1 best solutions below

0
Paula Serna On

Solution:

import gradio as gr

with gr.Blocks() as demo:

    radio = gr.Radio(["show", "hide"], label="Choose")
    text = gr.Textbox(label="This text only shows when 'show' is selected.", visible=False)

    
    def update_visibility(radio):  # Accept the event argument, even if not used
        value = radio  # Get the selected value from the radio button
        if value == "show":
            return gr.Textbox(visible=bool(1)) #make it visible
        else:
            return gr.Textbox(visible=bool(0))]
    radio.change(update_visibility, radio, text)

demo.launch()

If it doesn't work you can try to return with the update function: gr.Textbox.update(visible=bool(1))