Components are the fundamental building blocks of Gradio interfaces. They represent inputs, outputs, and interactive elements that users can engage with in your application.
What are components?
In Gradio, components are UI elements that:
- Display information to users (like text, images, or charts)
- Collect user input (like textboxes, sliders, or file uploads)
- Can be both inputs and outputs in the same interface
Every component in Gradio can preprocess data for your function and postprocess results for display.
Component types
Gradio provides over 30 built-in components across several categories:
Text components
- Textbox: Single or multi-line text input/output
- Markdown: Display formatted text with Markdown syntax
- HTML: Render custom HTML content
- Code: Code editor with syntax highlighting
- Label: Display classification results with confidence scores
- Image: Upload, display, or edit images
- Audio: Record or upload audio files
- Video: Upload or display video files
- File: Upload any file type
- Gallery: Display multiple images in a grid
Data components
- Dataframe: Interactive spreadsheet-like table
- JSON: Display structured JSON data
- HighlightedText: Show text with highlighted spans
- Dataset: Display example inputs
- Slider: Numeric input with min/max range
- Number: Numeric input field
- Checkbox: Boolean on/off toggle
- CheckboxGroup: Select multiple options
- Radio: Select one option from a list
- Dropdown: Dropdown menu for selections
- ColorPicker: Choose colors visually
- DateTime: Select dates and times
Layout components
- Button: Clickable button to trigger events
- ClearButton: Clear component values
- UploadButton: Upload files without a dedicated file component
- State: Store values between interactions (invisible)
Visualization components
- Plot: Display Plotly, Matplotlib, or Bokeh charts
- BarPlot, LinePlot, ScatterPlot: Native plot components
- Model3D: Display 3D models
- AnnotatedImage: Images with highlighted regions
Using components
As string shortcuts
For quick prototyping, use string shortcuts:
import gradio as gr
demo = gr.Interface(
fn=lambda x: x.upper(),
inputs="textbox", # String shortcut
outputs="textbox"
)
Common shortcuts: "textbox", "image", "audio", "video", "file", "dataframe", "slider", etc.
As component instances
For more control, instantiate components directly:
import gradio as gr
demo = gr.Interface(
fn=lambda x: x.upper(),
inputs=gr.Textbox(
label="Input Text",
placeholder="Enter text here...",
lines=3,
max_lines=10
),
outputs=gr.Textbox(label="Uppercase Result")
)
Common component parameters
Most components share these parameters:
Label and info
component = gr.Textbox(
label="Enter your name", # Main label above component
info="This will be used to personalize your greeting" # Helper text
)
Value
Set initial/default values:
textbox = gr.Textbox(value="Default text")
slider = gr.Slider(minimum=0, maximum=100, value=50)
checkbox = gr.Checkbox(value=True)
Interactive
Control whether users can modify the component:
# User can edit (default for inputs)
editable = gr.Textbox(interactive=True)
# Read-only display (default for outputs)
read_only = gr.Textbox(interactive=False)
Visibility
Show or hide components:
visible_box = gr.Textbox(visible=True)
hidden_box = gr.Textbox(visible=False)
# Toggle visibility with events
button.click(
fn=lambda: gr.Textbox(visible=True),
outputs=hidden_box
)
Styling
component = gr.Textbox(
elem_id="custom-textbox", # HTML element ID for CSS
elem_classes=["large-text", "bordered"], # CSS classes
scale=2, # Relative size in a Row (default=1)
min_width=300 # Minimum width in pixels
)
Component-specific features
Textbox
textbox = gr.Textbox(
lines=5, # Number of visible lines
max_lines=10, # Maximum expandable lines
placeholder="Type here...",
type="text", # "text" or "password"
show_copy_button=True, # Add copy button
autofocus=True # Focus on page load
)
Image
image = gr.Image(
type="pil", # "pil", "numpy", or "filepath"
source="upload", # "upload", "webcam", or "canvas"
tool="editor", # Enable image editing
height=300,
width=300
)
Slider
slider = gr.Slider(
minimum=0,
maximum=100,
step=5, # Increment size
value=50, # Default value
label="Temperature",
info="Controls randomness"
)
Dropdown
dropdown = gr.Dropdown(
choices=["Option 1", "Option 2", "Option 3"],
value="Option 1", # Default selection
multiselect=False, # Allow multiple selections
allow_custom_value=True, # Allow typing custom values
label="Select an option"
)
Dataframe
dataframe = gr.Dataframe(
value=[[1, 2, 3], [4, 5, 6]], # Initial data
headers=["A", "B", "C"], # Column headers
row_count=(2, "dynamic"), # (min_rows, max_rows or "dynamic")
col_count=(3, "fixed"), # (num_cols, "fixed" or "dynamic")
datatype=["number", "number", "str"], # Column types
interactive=True # Allow editing
)
Preprocessing and postprocessing
Components automatically transform data:
Image preprocessing
import gradio as gr
from PIL import Image
import numpy as np
def process_image(img):
# img is already a PIL Image (due to type="pil")
return img.rotate(90)
demo = gr.Interface(
fn=process_image,
inputs=gr.Image(type="pil"),
outputs=gr.Image()
)
Change type to control the input format:
type="pil" → PIL Image object
type="numpy" → NumPy array
type="filepath" → String path to file
Audio preprocessing
def process_audio(audio):
# audio is a tuple: (sample_rate, data)
sample_rate, data = audio
return (sample_rate, data * 2) # Double the volume
demo = gr.Interface(
fn=process_audio,
inputs=gr.Audio(),
outputs=gr.Audio()
)
File handling
def read_file(file):
# file is a file path string
with open(file, 'r') as f:
content = f.read()
return content
demo = gr.Interface(
fn=read_file,
inputs=gr.File(),
outputs=gr.Textbox()
)
Updating components dynamically
Update component properties during events:
import gradio as gr
def update_ui(choice):
if choice == "Show":
return gr.Textbox(visible=True, value="Now you see me!")
else:
return gr.Textbox(visible=False)
with gr.Blocks() as demo:
radio = gr.Radio(["Show", "Hide"], label="Toggle")
output = gr.Textbox(visible=False)
radio.change(fn=update_ui, inputs=radio, outputs=output)
You can update any component property:
def update_all():
return gr.Textbox(
value="New text",
label="Updated Label",
placeholder="New placeholder",
visible=True,
interactive=False,
lines=10
)
Special components
State
The State component stores data between interactions without displaying it:
import gradio as gr
def increment(count):
return count + 1, f"Count: {count + 1}"
with gr.Blocks() as demo:
state = gr.State(value=0) # Initial state
output = gr.Textbox()
btn = gr.Button("Increment")
btn.click(
fn=increment,
inputs=state,
outputs=[state, output]
)
State is session-specific - each user has their own isolated state.
Chatbot
The Chatbot component displays conversational messages:
import gradio as gr
import random
import time
def respond(message, chat_history):
bot_message = random.choice(["Hello!", "How are you?", "Nice day!"])
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
time.sleep(1)
return "", chat_history
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.ClearButton([msg, chatbot])
msg.submit(respond, [msg, chatbot], [msg, chatbot])
Creating custom components
You can create entirely custom components using Gradio’s custom component framework. See the custom components guide for details.
Component events
Different components support different events:
- All components:
.change() - When value changes
- Button:
.click() - When clicked
- Textbox:
.submit(), .input(), .focus(), .blur()
- File:
.upload(), .delete(), .download()
- Image:
.select(), .clear()
- Chatbot:
.retry(), .undo(), .like()
See the Events concept for complete details.
See also