gradio · difficulty ◆◆
gradio Tabs — split one demo into switchable panels
Tabs are layout, not routing: the panels stay alive, only events leave the browser.
Four things to show, one screen to show them on — and a `selected=` parameter that quietly ignores indices.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ gr.Tabs()- 3.0
- Shipped in
- 8
- gr.Tabs() params
- 14
- gr.Tab() params
- 2
- Events
16 May 2022, the same release that introduced Blocks
6.30.0 signature; 7 until overflow_behavior landed in 6.28.0
6.30.0 signature; it was 11 in 6.18.0
gr.Tabs: .change() and .select(); gr.Tab: .select() only
What it does
gr.Tabs is a layout container. Its direct children have to be gr.Tab blocks; each Tab is one panel plus one button in the bar. Only the selected panel is displayed. The `selected` argument decides which tab opens first and it takes the tab's **id**, not a position. Everything inside a tab works normally — event listeners, outputs, gr.State — and it keeps its values while you look at another tab.
Why it matters
Most demos have more than one job: the form, the result, the explanation, the logs. Stacked vertically they become a wall of boxes; with tabs the wall lives behind three buttons, and you didn't need a second app or a router. That's the cheapest information architecture Gradio offers, which is why nearly every Space with three or more outputs ends up here.
Example
$ import gradio as gr
def forecast(metric: str, days: int):
base = {"revenue": 418_000, "churn": 2.9, "signups": 1_240}[metric]
return f"**{metric}**: {base * (1 + days / 100):,.1f} in {days} days"
with gr.Blocks(title="Ops board") as demo:
with gr.Tabs(selected="forecast"):
with gr.Tab("Forecast", id="forecast"):
metric = gr.Dropdown(["revenue", "churn", "signups"], value="revenue", label="Metric")
days = gr.Slider(7, 90, value=30, step=1, label="Horizon (days)")
go = gr.Button("Forecast", variant="primary")
out = gr.Markdown()
go.click(forecast, [metric, days], out)
with gr.Tab("How it works", id="about"):
gr.Markdown("Pick a metric, pick a horizon, get a number.")
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
Rendered UI (headless Chromium, gradio 6.30.0):
- .tabs holds a [role=tablist] with two <button role=tab>: "Forecast" (aria-selected=true, data-tab-id=forecast) and "How it works"
- at load only the Forecast panel is in the DOM: Dropdown "Metric" (revenue / churn / signups), Slider "Horizon (days)" 7–90 step 1 with its ↺ reset icon, primary Button "Forecast", empty Markdown
- click Forecast -> Markdown renders "revenue: 543,400.0 in 30 days"
- click "How it works" -> Forecast panel switches to display:none, the second panel mounts with "Pick a metric, pick a horizon, get a number." Come back to Forecast and your dropdown choice and the last result are still there: tabs hide panels, they never reset them.
$ import datetime, gradio as gr
with gr.Blocks(title="Tab audit") as demo:
with gr.Tabs(selected="upload") as tabs:
with gr.Tab("Upload", id="upload"):
gr.Markdown("Step 1 — drop the CSV.")
with gr.Tab("Explore", id="explore"):
gr.Markdown("Step 2 — filter it.")
with gr.Tab("Results", id="results"):
gr.Markdown("Step 3 — export.")
seen = gr.Markdown("no tab visit yet")
skip = gr.Button("Skip to results")
def on_tab(evt: gr.SelectData):
stamp = datetime.datetime.now().strftime("%H:%M:%S")
return f"`{evt.value}` — label, index {evt.index}, seen at {stamp}"
tabs.select(on_tab, None, seen)
skip.click(lambda: gr.Tabs(selected="results"), None, tabs)
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
Rendered UI (verified on 6.30.0):
- three buttons in the bar: Upload (selected), Explore, Results
- clicking Explore fires the Python handler; the readout under the bar becomes
"Explore — label, index 1, seen at 09:39:03" (evt.value = label, evt.index = position among the visible tabs)
- clicking "Skip to results" -> Results has aria-selected=true, the Upload and Explore panels both sit at display:none, and the readout still says Explore: the programmatic switch does not fire .select()Type the handler parameter as gr.SelectData. A bare `lambda evt: evt.value` receives None — Gradio only injects the event when the annotation asks for it.
$ import gradio as gr
with gr.Blocks(title="Deep-linked tabs") as demo:
with gr.Tabs() as tabs:
with gr.Tab("Summary", id="summary"):
gr.Markdown("One paragraph, nothing else.")
with gr.Tab("Table", id="table"):
gr.Dataframe(headers=["date", "rows"], value=[["2026-10-17", 412]])
with gr.Tab("Logs", id="logs"):
gr.Code("2026-10-17 09:12 ingest ok (412 rows)", language="shell")
def open_tab(request: gr.Request):
wanted = (request.query_params.get("tab") or "summary").lower()
return gr.Tabs(selected=wanted)
demo.load(open_tab, None, tabs)
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
Same app, three URLs (verified on 6.30.0):
- / -> Summary selected, panel mounts, Table and Logs have no panel at all yet
- /?tab=logs -> Logs button aria-selected=true, Code component mounts with the line "2026-10-17 09:12 ingest ok (412 rows)"
- /?tab=table -> Table selected, Dataframe renders its two headers (date, rows) and the single row 2026-10-17 / 412
demo.load() returns gr.Tabs(selected="logs"), and the bar follows — no page reload.The query value is matched against tab ids after .lower(). An id that doesn't exist (?tab=nope) selects nothing and you get an empty area under the bar — validate before returning.
$ import gradio as gr
LABELS = ["Revenue forecast", "Churn analysis", "Cohort retention", "Pipeline health",
"Model metrics", "Data quality", "Segment explorer", "Alerts & incidents"]
with gr.Blocks() as demo:
with gr.Tabs(overflow_behavior="wrap"): # "menu" is the default
for i, label in enumerate(LABELS):
with gr.Tab(label, id=f"t{i}"):
gr.Markdown(f"{label} panel")
demo.launch()* Running on local URL: http://127.0.0.1:7860
* To create a public link, set `share=True` in `launch()`.
Eight long labels, 520 px viewport (verified on 6.30.0):
- overflow_behavior="menu" (default): bar is 32 px tall with 2 buttons on it; the other 6 labels live in the ⋯ dropdown; tablist flex-wrap is nowrap, overflow hidden
- overflow_behavior="wrap": all 8 buttons visible, tablist 96 px tall (3 rows), no .overflow-menu element in the DOM at all
- picking "Model metrics" from the dropdown sets aria-selected=true on it and mounts its paneloverflow_behavior arrived in 6.28.0 (18 Sep 2026). Before that the ⋯ menu was the only option — and tabs with visible=False never appear in it (fixed in 5.29.1).
Common flags
- id=
- Name the tab. It becomes data-tab-id on the button and the value `selected` looks up.
- selected=
- Which tab opens first — an id string (or a numeric id), never a list index.
- visible=
- False on a gr.Tab removes it from the bar completely: no button, no overflow entry.
- overflow_behavior=
- 'menu' collapses extra tabs into ⋯, 'wrap' grows the bar into rows (6.28.0+).
- .select(fn, None, out)
- Fires on a real tab change with gr.SelectData: .value is the label, .index the position.
- elem_id=
- On gr.Tabs it lands on the .tabs div; on gr.Tab on the .tabitem panel, not the button.
- gr.Tabs(selected=...)
- Return it into the tabs component to move the user from a handler — no select event follows.
History
Tabs arrived with Blocks, not after it
Gradio 3.0 (16 May 2022) shipped Blocks and with it the first layouts: Row, Column, Group, Tabs, TabItem. The release notes list "Group together related demos as multiple tabs in one web app" as one of the reasons Blocks exists at all. That first version of Tabs had no constructor arguments whatsoever — `selected` and per-tab `id` only arrived in 3.2.
The class that renamed itself
gr.Tab appeared in 3.2 (31 Aug 2022) beside the original gr.TabItem, which turned into an alias; `gr.TabItem is gr.Tab` still returns True in 6.30.0. The bar got a full redesign for the 5.0 beta (PR #9199), and the small fixes never stopped: 6.20.0 (7 Jul 2026) made .select() fire again, 6.28.0 made overflow configurable, 6.29.0 added height/max_height to a single Tab.
Under the hood
One panel in the DOM, the rest waiting
Inspect a running app and you find one .tabitem per tab you have visited: the active one at display:flex, the rest at display:none. A tab nobody clicked has no panel element at all, so a heavy Dataframe in tab 3 costs no DOM until it is opened — though its components are still serialized in /config, so "lazy" covers rendering, not the payload. The bar itself is a <button role="tab" data-tab-id="..."> row, and right beside the visible tablist Gradio keeps a second, aria-hidden copy of the same buttons: it exists purely to measure label widths when deciding how many tabs fit before the rest collapse into the ⋯ menu. All of that read off a live 6.30.0 page.
Fun facts
Pros & cons
pros
- + One container, one block per screen — no routes, no callbacks, no second app.
- + Panels keep their component state, so a form and its result can live apart without losing input.
- + Everything nests: events, gr.State, gr.render, Rows inside tabs all behave as usual.
cons
- − No URL per tab by default; deep links need the demo.load + gr.Request trick.
- − An unknown `selected` value fails silently into an empty app.
- − Every tab is in the config payload even when no panel is mounted.
Takeaways
- 1Give every tab an id; `selected` matches ids, and a wrong value silently renders no panel.
- 2Type-hint the select handler as gr.SelectData or the event arrives as None.
- 3Move the user with `return gr.Tabs(selected="results")` into the tabs component — and don't expect .select() to fire.
- 4Put the expensive panel in a later tab; unvisited tabs have no DOM at all.
- 5On narrow layouts use overflow_behavior="wrap" so the ⋯ menu can't hide your primary tabs.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
