Chuyển đến nội dung

Bài 14 · Blocks and Layouts

Dynamic UI: Visibility, Updates and render

Make a Gradio page change as users interact: toggle visibility, return updated component properties, swap choices, and build components from data with the @gr.render decorator.

A static page is fine for a one-shot demo, but real apps adapt: advanced options appear after ticking a box, a Dropdown's choices depend on another Dropdown, a list of items grows as the user adds them. Gradio supports this in three ways: changing the properties of existing components (visibility, interactivity, choices, labels), returning new values to components, and re-rendering parts of the page from data with @gr.render. Gradio code is read-only; stand-ins model each mechanism.

Changing component properties

An event function can return a new component or a gr.update(...)-style dictionary, and Gradio applies the changes to the existing component in the browser. In current versions, returning a component instance of the same type works as an update; the older gr.update(visible=True) form still works in many versions.

Python
import gradio as gr

def toggle(show):
    return gr.Textbox(visible=show)

with gr.Blocks() as demo:
    show = gr.Checkbox(label="Show notes field")
    notes = gr.Textbox(label="Notes", visible=False)
    show.change(toggle, show, notes)

The page starts with just a checkbox. Ticking it makes the Notes box appear, and clearing it hides the box again. The properties you will change most often:

Property Use
visible Show or hide a component or a whole container (Row, Column, Accordion)
interactive Enable or disable editing
choices Replace the options of a Dropdown or Radio
value Set a new value (also possible by returning the value directly)
label, info, placeholder Change texts

Only properties you pass are changed; the rest stay. When a component is hidden (visible=False) it is not drawn, but it still exists in the app's definition.

Dependent dropdowns

Python
CITIES = {"Norway": ["Oslo", "Bergen"], "Peru": ["Lima", "Cusco", "Arequipa"]}

def update_cities(country):
    cities = CITIES[country]
    return gr.Dropdown(choices=cities, value=cities[0])

with gr.Blocks() as demo:
    country = gr.Dropdown(list(CITIES), label="Country", value="Norway")
    city = gr.Dropdown(CITIES["Norway"], label="City", value="Oslo")
    country.change(update_cities, country, city)

Choosing Peru replaces the City options with Lima, Cusco and Arequipa and selects Lima. Always set a value that is inside the new choices, or you will see warnings and an empty field.

Showing a whole section

Hiding a container is cleaner than hiding many components:

Python
with gr.Blocks() as demo:
    mode = gr.Radio(["Simple", "Advanced"], value="Simple", label="Mode")
    with gr.Column(visible=False) as advanced:
        gr.Slider(0, 1, label="Temperature")
        gr.Number(label="Seed")
    mode.change(lambda m: gr.Column(visible=(m == "Advanced")), mode, advanced)

Hidden inputs still keep their values, and visible-only logic belongs in your function: do not assume hidden inputs are empty.

Rendering from data with @gr.render

Sometimes you do not know how many components you need. @gr.render re-runs a function when its trigger inputs change and rebuilds the components inside it:

Python
with gr.Blocks() as demo:
    items = gr.State(["milk", "eggs"])
    new = gr.Textbox(label="New item")
    add = gr.Button("Add")

    def add_item(current, text):
        return current + [text] if text else current

    add.click(add_item, [items, new], items)

    @gr.render(inputs=items)
    def show_items(current):
        for index, name in enumerate(current):
            with gr.Row():
                gr.Textbox(name, label=f"Item {index + 1}", interactive=False)
                gr.Button("Remove").click(
                    lambda cur, i=index: cur[:i] + cur[i + 1:], items, items
                )

The page lists one row per item, each with a Remove button. Adding "bread" re-runs show_items, producing three rows. Event listeners created inside @gr.render are scoped to the render block and use default arguments (i=index) to capture the loop variable, the same trick as with Python closures. Use render for to-do lists, forms with repeating sections and tabs generated from data. Because it rebuilds the page part, avoid it for large lists or for components that must keep focus while typing.

Choosing a technique

Situation Technique
Show or hide something visible on component or container
Options depend on another choice return Dropdown(choices=...)
Number of components depends on data @gr.render
Different layouts for a few cases Tabs or hidden Columns
flowchart LR
    E["Event fires"] --> F["Function runs"]
    F -->|"returns value"| V["Set value"]
    F -->|"returns component"| P["Update properties"]
    F -->|"state changed"| R["@gr.render rebuilds"]

Three ways a function can change the page.

Stand-in 1: property updates

This stand-in keeps components as dictionaries and applies a partial update the way Gradio applies a returned component.

Python Stand-in: partial property updates

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The label of notes stayed because the update touched only visible. That partial-update rule is why returning a component changes only what you set.

Stand-in 2: re-rendering a list from state

Python Stand-in: render a list from data

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that add_item creates a new list instead of mutating the old one. Gradio compares state values to detect changes, and a mutated list that is the same object may not trigger a rebuild.

Pitfalls

  • Returning a different component type (a Textbox where a Number lives) is not a valid update.
  • Forgetting a value after changing choices.
  • Too much hiding: if a screen reader user cannot find a feature, hide it with visible=False, which removes it from the accessibility tree, only when it is truly irrelevant.
  • Heavy @gr.render on large data slows the page; show the first 20 items and a "Load more" button instead.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What happens to other properties when an update sets only visible=True?

    Updates are partial: only the properties you provide change.
  2. 2. When you replace a Dropdown's choices, what should value be?

    A value outside the new choices leaves an invalid state.
  3. 3. Which tool builds a variable number of components from data?

    @gr.render re-runs and rebuilds its block whenever its input state changes.
  4. 4. Why return a new list instead of calling append on the state list?

    Creating a new object makes the change visible to the framework.

Summary

  • Return components or updates to change visible, interactive, choices, label and value.
  • Hide whole containers for optional sections; hidden inputs still keep values.
  • Dependent dropdowns need a valid value among the new choices.
  • @gr.render builds components from data; keep lists small and replace state objects.

Next: Event Listeners

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.