INTRODUCTION TO `gr.blocks`: 10 REAL-TIME FLEXIBLE LAYOUT EXAMPLES

Master Gradio's flexible `gr.Blocks` architecture with 10 real-world layout examples featuring custom rows, columns, tabs, markdown headers, and multi-component dashboards.

⚡ Beyond `gr.Interface`: Flexible Layouts with Blocks

While gr.Interface provides quick linear layouts, gr.Blocks gives developers complete design freedom. It allows you to group components into custom rows, vertical columns, tabbed panes, and multi-step dashboards with precise control over event listeners.

Example 1: Basic Two-Column Layout
Places input and output components side-by-side using horizontal column blocks.
Python (block_ex1.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("## Two-Column Layout Demo")
    with gr.Row():
        with gr.Column():
            txt_in = gr.Textbox(label="Input Text")
            btn = gr.Button("Process")
        with gr.Column():
            txt_out = gr.Textbox(label="Output Result")
            
    btn.click(fn=lambda x: x.upper(), inputs=txt_in, outputs=txt_out)

if __name__ == "__main__":
    demo.launch()
Layout Structure: gr.Row() containing two distinct gr.Column() containers side-by-side.
Example 2: Tabbed Multi-Model Application Dashboard
Organizes separate AI tools (Text Summarizer & Image Filter) into clean tabbed panels.
Python (block_ex2.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("# Enterprise AI Suite")
    with gr.Tabs():
        with gr.Tab("Text Summarizer"):
            t_in = gr.Textbox(label="Long Article")
            t_out = gr.Textbox(label="Summary")
            gr.Button("Summarize").click(lambda x: x[:50] + "...", t_in, t_out)
            
        with gr.Tab("Image Grayscale"):
            i_in = gr.Image(label="Original Photo")
            i_out = gr.Image(label="Grayscale")
            gr.Button("Convert").click(lambda img: img, i_in, i_out)

if __name__ == "__main__":
    demo.launch()
Layout Structure: gr.Tabs() wrapping individual gr.Tab() components for modular tool organization.
Example 3: Collapsible Advanced Settings Accordion
Hides secondary configuration options inside an expandable accordion container.
Python (block_ex3.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("### Image Generation Studio")
    prompt = gr.Textbox(label="Main Prompt", value="A futuristic city")
    
    with gr.Accordion("Advanced Generation Settings", open=False):
        steps = gr.Slider(10, 100, value=30, label="Inference Steps")
        guidance = gr.Slider(1, 20, value=7.5, label="Guidance Scale")
        seed = gr.Number(value=42, label="Random Seed")
        
    btn = gr.Button("Generate Image", variant="primary")

if __name__ == "__main__":
    demo.launch()
Layout Structure: gr.Accordion() toggle container keeping complex settings clean and collapsed by default.
Example 4: Multi-Step Calculator Dashboard
Combines numeric inputs, operation selectors, and result grids into a unified dashboard.
Python (block_ex4.py)
import gradio as gr

def compute(a, b, op):
    if op == "Add": return a + b
    elif op == "Subtract": return a - b
    elif op == "Multiply": return a * b
    else: return a / b if b != 0 else "Error: Division by zero"

with gr.Blocks() as demo:
    gr.Markdown("## Advanced Math Engine")
    with gr.Row():
        num1 = gr.Number(value=10, label="Operand A")
        num2 = gr.Number(value=5, label="Operand B")
    op = gr.Radio(["Add", "Subtract", "Multiply", "Divide"], value="Add", label="Operation")
    btn = gr.Button("Calculate")
    res = gr.Textbox(label="Result Output")
    
    btn.click(compute, [num1, num2, op], res)

if __name__ == "__main__":
    demo.launch()
Layout Structure: Multi-row block structure grouping calculation parameters cleanly.
Example 5: Interactive Chatbot Window with Custom Blocks
Builds a custom chat layout combining a chatbot display window, textbox input, and clear button.
Python (block_ex5.py)
import gradio as gr

def bot_respond(message, history):
    return history + [[message, f"Echo response: {message}"]]

with gr.Blocks() as demo:
    gr.Markdown("# Nikita AI Assistant")
    chatbot = gr.Chatbot(label="Conversation History")
    msg = gr.Textbox(label="Type your message here...")
    clear = gr.Button("Clear Chat")
    
    msg.submit(bot_respond, [msg, chatbot], [chatbot])
    clear.click(lambda: [], None, chatbot)

if __name__ == "__main__":
    demo.launch()
Layout Structure: Vertical stack combining gr.Chatbot, input box, and action buttons inside gr.Blocks.
Example 6: Split-Screen Code Editor & Previewer
Presents an input code editor side-by-side with a rendered preview window.
Python (block_ex6.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("### Live Markdown Studio")
    with gr.Row():
        with gr.Column():
            editor = gr.Code(language="markdown", label="Markdown Source", value="# Hello Nikita")
        with gr.Column():
            preview = gr.Markdown(label="Live Preview")
            
    editor.change(lambda x: x, editor, preview)

if __name__ == "__main__":
    demo.launch()
Layout Structure: 50/50 split column layout executing live reactive preview updates on code modification.
Example 7: Multi-Step Form Wizard with Next/Back Navigation
Simulates a multi-step user onboarding wizard using visibility toggles across blocks.
Python (block_ex7.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("## User Onboarding Wizard")
    
    with gr.Column(visible=True) as step1:
        gr.Markdown("### Step 1: Personal Info")
        name = gr.Textbox(label="Full Name")
        next1 = gr.Button("Next ➔")
        
    with gr.Column(visible=False) as step2:
        gr.Markdown("### Step 2: Account Details")
        email = gr.Textbox(label="Email Address")
        back2 = gr.Button("⬅ Back")
        finish = gr.Button("Complete Registration ✔")
        
    next1.click(lambda: (gr.update(visible=False), gr.update(visible=True)), None, [step1, step2])
    back2.click(lambda: (gr.update(visible=True), gr.update(visible=False)), None, [step1, step2])

if __name__ == "__main__":
    demo.launch()
Layout Structure: Conditional column visibility toggling to achieve multi-step wizard navigation.
Example 8: Multi-Modal Data Analysis Dashboard
Combines tabular CSV file viewers, filter controls, and matplotlib charts into a unified dashboard.
Python (block_ex8.py)
import gradio as gr
import pandas as pd

with gr.Blocks() as demo:
    gr.Markdown("# Enterprise Analytics Dashboard")
    with gr.Row():
        file_box = gr.File(label="Upload Dataset (CSV)")
        filter_box = gr.Textbox(label="Search Filter Term")
    data_grid = gr.Dataframe(label="Filtered Records")
    
    file_box.upload(lambda f: pd.read_csv(f.name) if f else pd.DataFrame(), file_box, data_grid)

if __name__ == "__main__":
    demo.launch()
Layout Structure: Top row controls paired with a wide bottom data table grid container.
Example 9: Notification Banner & Status Alert Blocks
Uses HTML/Markdown alert boxes to display dynamic system status messages.
Python (block_ex9.py)
import gradio as gr

def check_status(api_key):
    if api_key == "secret123":
        return "
✅ API Key Verified Successfully!
" else: return "
❌ Invalid API Key Provided.
" with gr.Blocks() as demo: gr.Markdown("### System Authentication Status") key_input = gr.Textbox(label="Enter API Key", type="password") status_box = gr.HTML() key_input.change(check_status, key_input, status_box) if __name__ == "__main__": demo.launch()
Layout Structure: Standard input widget paired with an HTML rendering block for styled alert banners.
Example 10: Complete Full-Stack AI Application Hub
A master dashboard integrating header banners, sidebars, multi-tab tools, and footer info.
Python (block_ex10.py)
import gradio as gr

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("

🚀 Nikita Infotech Enterprise AI Hub

") with gr.Tabs(): with gr.Tab("Image Generation"): with gr.Row(): gr.Textbox(label="Prompt") gr.Button("Generate") gr.Image(label="Output Canvas") with gr.Tab("Text Translation"): with gr.Row(): gr.Dropdown(["English", "Hindi", "French"], label="Target Language") gr.Textbox(label="Source Text") gr.Textbox(label="Translated Output") gr.Markdown("

© 2026 Nikita Infotech | Powered by Gradio Blocks

") if __name__ == "__main__": demo.launch()
Layout Structure: Complete production-grade layout combining custom themes, headers, tabbed workspaces, and footers.