Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Blocks and Layouts

Blocks Basics

Learn gr.Blocks, Gradio's low-level API: build a page with a context manager, place components, attach click handlers, and understand how it relates to Interface.

gr.Blocks is the flexible side of Gradio. Instead of handing over one function and two lists, you describe the page: you open a with gr.Blocks() as demo: block, create components inside it in the order you want them to appear, and then connect them to functions with event listeners such as click. Everything Interface does can be done with Blocks, plus multiple functions, custom layouts, outputs that feed other inputs and dynamic behaviour. The Gradio code is read-only; a runnable stand-in implements a tiny Blocks so the mechanics are clear.

The first Blocks app

Python
import gradio as gr

def add(a, b):
    return a + b

with gr.Blocks(title="Calculator") as demo:
    gr.Markdown("# Calculator")
    a = gr.Number(label="A")
    b = gr.Number(label="B")
    total = gr.Number(label="Sum", interactive=False)
    button = gr.Button("Add", variant="primary")
    button.click(fn=add, inputs=[a, b], outputs=total)

demo.launch()

The page shows a heading, two number boxes, a read-only Sum box and a blue Add button. Clicking it calls add with the values of a and b and writes the result into total.

Three pieces to remember:

  1. Components created inside the with block are placed on the page in order. The context manager is what registers them.
  2. Components are Python objects, so you can keep them in variables and refer to them later (inputs=[a, b]). This is the biggest difference from Interface.
  3. Events are wired explicitly: component.event(fn, inputs, outputs).

Components inside Blocks

All the components from the previous chapter work the same way. Two differences:

  • Button, Markdown and HTML are used constantly because you build your own page.
  • Input components are interactive by default and output components are not, but in Blocks the same component can be both: it is an output of one event and an input of another. Set interactive=True or False to control this.
Python
with gr.Blocks() as demo:
    name = gr.Textbox(label="Name")
    greeting = gr.Textbox(label="Greeting", interactive=False)
    gr.Button("Greet").click(lambda n: f"Hello, {n}!", name, greeting)

A single component can be passed as inputs or outputs without a list, and a lambda is fine for one-liners (a named function gives a clearer API name, see examples, flagging and API names).

Several functions on one page

This is where Blocks pays off. Two independent tools can share a page:

Python
with gr.Blocks() as demo:
    gr.Markdown("## Two tools")
    with gr.Row():
        with gr.Column():
            text = gr.Textbox(label="Text")
            count = gr.Number(label="Words", interactive=False)
            text.change(lambda t: len(t.split()), text, count)
        with gr.Column():
            number = gr.Number(label="Number")
            squared = gr.Number(label="Squared", interactive=False)
            number.change(lambda n: (n or 0) ** 2, number, squared)

text.change(...) fires on every edit, so the word count updates as you type. Row and Column place the tools side by side; the next lesson explains layouts in detail.

Interface versus Blocks

Interface Blocks
Functions One Any number
Layout Fixed form You design it
Events Submit and live click, change, select, load and more
Code size Smallest More lines, more control
Under the hood A prebuilt Blocks The foundation

You can mix them: build panels as Interface objects and combine them with gr.TabbedInterface, or call iface.render() inside a Blocks block. Many apps start as Interface and move to Blocks when someone asks for "a second button".

flowchart TD
    B["with gr.Blocks() as demo"] --> L["Layout: Row, Column, Tab"]
    B --> C["Components"]
    B --> E["Events: click, change, ..."]
    E -->|"fn, inputs, outputs"| F["Your functions"]

Blocks has three ingredients: layout, components and event wiring.

The Blocks object

demo is more than a page. It has methods you will use throughout the track: demo.launch(), demo.queue() for concurrency settings, demo.load(fn, ...) for page-load events, and attributes such as demo.config (the JSON description sent to the browser). Printing demo.config["components"] is a good way to see what you built.

Components also have an ID. When two events write to the same output, the last one to finish wins, so give related events a single output or chain them (see event chaining).

Stand-in 1: a miniature Blocks

This stand-in is our own code. It records components in a list and routes an event by name, which is the core of the real thing.

Python Stand-in: components, events and routing

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.

Stand-in 2: two independent tools

Python Stand-in: two tools on one page

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.

Events are independent: editing the text recomputes only the word count, never the square. That independence is what Blocks gives you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the with gr.Blocks() as demo: block do?

    The context manager collects components and layout. launch() starts the server later.
  2. 2. How do you run a function when a button is pressed in Blocks?

    Event listeners such as click connect a component event to a function, its inputs and its outputs.
  3. 3. Which is a reason to choose Blocks over Interface?

    Blocks gives control over layout and events at the cost of more code.
  4. 4. Two events write to the same output at nearly the same time. What happens?

    The output shows whichever result arrived last, so design events to avoid races.

Summary

  • with gr.Blocks() as demo: builds a page from components in order.
  • Wire behaviour explicitly with component.event(fn, inputs, outputs).
  • One page can hold many independent functions.
  • Interface is a convenience layer over Blocks; the two can be combined.

Next: Rows, Columns and Tabs