python系列&deep_study系列:Gradio中文教程(十)Controlling Layout
Gradio中文教程(十)Controlling Layout
Gradio中文教程(十)Controlling Layout
控制布局
默认情况下,Blocks
中的组件是垂直排列的。让我们看看如何重新排列组件。在底层,这种布局结构使用了Web开发的flexbox模型
。
行
在with gr.Row
子句中的元素将全部水平显示。例如,要并排显示两个按钮:
with gr.Blocks() as demo:
with gr.Row():
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")
要使行中的每个元素具有相同的高度,请使用style方法
的equal_height参数
。
with gr.Blocks() as demo:
with gr.Row(equal_height=True):
textbox = gr.Textbox()
btn2 = gr.Button("Button 2")
行中元素的宽度可以通过每个组件中存在的scale
和min_width
参数的组合来控制。
scale
是一个整数,定义元素在行中如何占用空间。如果scale
设置为0
,元素将不会扩展以占用空间。如果scale
设置为1
或更大,元素将扩展。行中的多个元素将根据它们的scale
按比例扩展。下面,btn2
将比btn1
扩展两倍,而btn0
根本不会扩展:
with gr.Blocks() as demo:
with gr.Row():
btn0 = gr.Button("Button 0", scale=0)
btn1 = gr.Button("Button 1", scale=1)
btn2 = gr.Button("Button 2", scale=2)
min_width
将设置元素将占用的最小宽度。如果空间不足以满足所有min_width
值,行将换行。
在文档中了解更多关于行的信息。
列和嵌套
列内的组件将垂直堆叠在一起。由于垂直布局是Blocks应用程序
的默认布局,为了有用,列通常嵌套在行内。例如:
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
text1 = gr.Textbox(label="t1")
slider2 = gr.Textbox(label="s2")
drop3 = gr.Dropdown(["a", "b", "c"], label="d3")
with gr.Row():
with gr.Column(scale=1, min_width=600):
text1 = gr.Textbox(label="prompt 1")
text2 = gr.Textbox(label="prompt 2")
inbtw = gr.Button("Between")
text4 = gr.Textbox(label="prompt 1")
text5 = gr.Textbox(label="prompt 2")
with gr.Column(scale=2, min_width=600):
img1 = gr.Image("images/cheetah.jpg")
btn = gr.Button("Go")
demo.launch()
看看第一列如何有两个垂直排列的文本框。第二列有一个图像和按钮垂直排列。注意两个列的相对宽度是如何通过scale参数
设置的。具有两倍scale值
的列占用两倍的宽度。
在文档中了解更多关于列的信息。
尺寸
您可以控制各种组件的高度和宽度,其中参数可用。这些参数接受一个数字(解释为像素)或一个字符串。使用字符串允许直接将任何CSS单位
应用于封装的Block元素,以满足更具体的设计要求。当省略时,Gradio使用适合大多数用例的默认尺寸。
下面是一个使用视口宽度(vw
)的示例:
import gradio as gr
with gr.Blocks() as demo:
im = gr.ImageEditor(
width="50vw",
)
demo.launch()
当使用百分比值作为尺寸时,您可能希望定义一个具有绝对单位(例如px
或vw
)的父组件。这种方法确保具有相对尺寸的子组件能够适当地调整大小:
import gradio as gr
css = """
.container {
height: 100vh;
}
"""
with gr.Blocks(css=css) as demo:
with gr.Column(elem_classes=["container"]):
name = gr.Chatbot(value=[["1", "2"]], height="70%")
demo.launch()
在这个例子中,Column布局组件
被赋予了视口高度(100vh
)的100%高度
,而其中的Chatbot组件
占据了Column高度
的70%
。
您可以为这些参数应用任何有效的CSS单位
。有关CSS单位
的完整列表,请参考本指南。我们建议您始终考虑响应性,并在不同的屏幕尺寸上测试您的界面,以确保一致的用户体验。
标签和折叠面板
您还可以使用with gr.Tab('tab_name'):子句
创建标签。在with gr.Tab('tab_name'):上下文
中创建的任何组件都会出现在该标签中。连续的Tab子句
被分组在一起,因此一次只能选择一个标签,并且只显示该标签上下文内的组件。
例如:
import numpy as np
import gradio as gr
def flip_text(x):
return x[::-1]
def flip_image(x):
return np.fliplr(x)
with gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.")
with gr.Tab("Flip Text"):
text_input = gr.Textbox()
text_output = gr.Textbox()
text_button = gr.Button("Flip")
with gr.Tab("Flip Image"):
with gr.Row():
image_input = gr.Image()
image_output = gr.Image()
image_button = gr.Button("Flip")
with gr.Accordion("Open for More!", open=False):
gr.Markdown("Look at me...")
temp_slider = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.1,
step=0.1,
interactive=True,
label="Slide me",
)
temp_slider.change(lambda x: x, [temp_slider])
text_button.click(flip_text, inputs=text_input, outputs=text_output)
image_button.click(flip_image, inputs=image_input, outputs=image_output)
demo.launch()
还要注意这个例子中的gr.Accordion('label')
。折叠面板是一种可以切换打开或关闭的布局。与Tabs
类似,它是一个可以有选择地隐藏或显示内容的布局元素。在with gr.Accordion('label'):内定义
的任何组件将在点击折叠面板的切换图标时隐藏或显示。
在文档中了解更多关于标签和折叠面板的信息。
可见性
组件和布局元素都有一个visible参数
,可以设置初始值并更新。在Column
上设置gr.Column(visible=...)
可以用来显示或隐藏一组组件。
import gradio as gr
with gr.Blocks() as demo:
error_box = gr.Textbox(label="Error", visible=False)
name_box = gr.Textbox(label="Name")
age_box = gr.Number(label="Age", minimum=0, maximum=100)
symptoms_box = gr.CheckboxGroup(["Cough", "Fever", "Runny Nose"])
submit_btn = gr.Button("Submit")
with gr.Column(visible=False) as output_col:
diagnosis_box = gr.Textbox(label="Diagnosis")
patient_summary_box = gr.Textbox(label="Patient Summary")
def submit(name, age, symptoms):
if len(name) == 0:
return {error_box: gr.Textbox(value="Enter name", visible=True)}
return {
output_col: gr.Column(visible=True),
diagnosis_box: "covid" if "Cough" in symptoms else "flu",
patient_summary_box: f"{name}, {age} y/o",
}
submit_btn.click(
submit,
[name_box, age_box, symptoms_box],
[error_box, diagnosis_box, patient_summary_box, output_col],
)
demo.launch()
可变数量的输出
通过以动态方式调整组件的可见性,可以创建支持可变数量输出的Gradio演示
。这里有一个非常简单的例子,其中输出文本框的数量由输入滑块控制:
import gradio as gr
max_textboxes = 10
def variable_outputs(k):
k = int(k)
return [gr.Textbox(visible=True)]*k + [gr.Textbox(visible=False)]*(max_textboxes-k)
with gr.Blocks() as demo:
s = gr.Slider(1, max_textboxes, value=max_textboxes, step=1, label="How many textboxes to show:")
textboxes = []
for i in range(max_textboxes):
t = gr.Textbox(f"Textbox {i}")
textboxes.append(t)
s.change(variable_outputs, s, textboxes)
if __name__ == "__main__":
demo.launch()
单独定义和渲染组件
在某些情况下,您可能希望在实际将组件渲染到UI
之前定义它们。例如,您可能希望使用gr.Examples
显示一个示例部分,该部分位于相应的gr.Textbox
输入之上。由于gr.Examples
需要作为参数的输入组件对象,您需要首先定义输入组件,然后在定义了gr.Examples对象
之后再渲染它。
解决这个问题的方法是在gr.Blocks()范围之外定义gr.Textbox
,并使用组件的.render()方法
在UI
中您希望放置它的任何位置。
这里有一个完整的代码示例:
input_textbox = gr.Textbox()
with gr.Blocks() as demo:
gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
input_textbox.render()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)