Skip to main content
Blocks is Gradio’s low-level API that gives you complete control over your application’s layout, events, and data flow. While Interface is great for simple demos, Blocks allows you to create sophisticated multi-page applications with custom interactions.

What is Blocks?

Blocks provides more flexibility than Interface by allowing you to:
  1. Control layout - Arrange components exactly how you want using rows, columns, tabs, and accordions
  2. Define custom events - Trigger functions based on any component interaction (clicks, changes, submissions)
  3. Create data flows - Chain events together so outputs from one function become inputs to another
  4. Build multi-page apps - Group related demos with tabs or separate pages

Basic structure

Blocks uses a context manager (the with statement) to define your application:
Key points:
  • Components defined inside the with block are automatically added to the interface
  • Events are set up using component methods like .change(), .click(), etc.
  • You define the function (welcome), inputs (inp), and outputs (out) for each event

Layout components

Rows and Columns

Organize components horizontally and vertically:

Tabs

Create tabbed interfaces for multiple workflows:

Accordions

Hide advanced options in collapsible sections:

Event listeners

Blocks allows you to attach event listeners to components to trigger functions:

Click events

Change events

Trigger when a component’s value changes:

Submit events

Trigger when the user presses Enter in a textbox:

Chaining events

One of Blocks’ most powerful features is event chaining with .then(), .success(), and .failure():
.then() runs after the previous event completes (regardless of success/failure), .success() runs only on success, and .failure() runs only on errors.

Multiple inputs and outputs

Pass lists of components for functions that need multiple inputs or produce multiple outputs:

State management

Use the State component to maintain values between interactions:
State components are not visible in the UI but persist values across function calls for each user session.

Queue and concurrency

Enable queueing to handle multiple users and long-running functions:

Rendering dynamically

Components render as soon as they’re created within a Blocks context. Set render=False to prevent automatic rendering:

Advanced features

Custom JavaScript

Run JavaScript code before or after Python functions:

Load events

Run functions when the page loads:

Cancelling events

Cancel running events when a new event starts:

Configuration

Blocks supports various configuration options:

When to use Blocks

Use Blocks when you need:
  • Custom layouts beyond simple input/output
  • Multiple related functions in one interface
  • Complex event chains and data flows
  • Multi-page or tabbed applications
  • Advanced state management
For simple function wrapping, consider using Interface instead.

See also