Python - Gradio uses Blocks to build custom interface layout applications

What are Blocks

Blocks is Gradio's low-level API that allows you to create more custom web applications and presentations than Interfaces. Simply put, it is more flexible than Interfaces.
Generally use context management, the sample code is as follows:

import gradio as gr

with gr.Blocks() as demo:
	gr.Image("lion.jpg", scale=2)
	gr.Image("tiger.jpg", scale=1)
demo.launch()

Layout of Blocks

Since it is more flexible, you can decide how to layout the interface.
If no layout is provided, the components are arranged vertically by default.

Row、Column

row layout and column layout

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            gr.Text(value='1')
            gr.Text(value='2')
        with gr.Column():
            gr.Text(value='3')
            gr.Text(value='4')
demo.launch()

insert image description here

Tab

Tab layout

with gr.Blocks(title='test Blocks') as demo:  # title可以修改页面标题
    with gr.Tab('标签页1'):
        gr.Text(value='1')
        gr.Text(value='2')
    with gr.Tab('标签页2'):
        gr.Text(value='3')
        gr.Text(value='4')
demo.launch()

insert image description here
insert image description here

Box

Box layout. Just put the components in the same box, personally think it is useless, basically never used.
Maybe I can’t see any changes without mentioning it. Compared with the first picture, you will find that the seam in the middle is gone, that is, all the components in the Box are put in the same box, and the first picture is two boxes.

with gr.Blocks(title='test Blocks') as demo:
    with gr.Box():
        with gr.Row():
            with gr.Column():
                gr.Text(value='1')
                gr.Text(value='2')
            with gr.Column():
                gr.Text(value='3')
                gr.Text(value='4')
demo.launch()

insert image description here

Accordion

This layout is to hide the components.

with gr.Blocks(title='test Blocks') as demo:
    with gr.Accordion("See Details"):
        with gr.Row():
            with gr.Column():
                gr.Text(value='1')
                gr.Text(value='2')
            with gr.Column():
                gr.Text(value='3')
                gr.Text(value='4')
demo.launch()

insert image description here
insert image description here

Summarize

In short, using Blocks() to build programs is definitely much more flexible than using Inferfaces().
This article only talks about using Blocks to customize the interface layout. In the next article, we will continue to talk about custom component triggering events .

Guess you like

Origin blog.csdn.net/DreamingBetter/article/details/131706319