默认情况下,Blocks 中的组件是垂直排列的。让我们看看如何重新排列组件。在底层,这种布局结构使用了网页开发中的 flexbox 模型。
with gr.Row 子句中的元素将全部水平显示。例如,要并排放置两个按钮
with gr.Blocks() as demo:
with gr.Row():
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")您可以设置 Row 中的每个元素都具有相同的高度。使用 equal_height 参数进行配置。
with gr.Blocks() as demo:
with gr.Row(equal_height=True):
textbox = gr.Textbox()
btn2 = gr.Button("Button 2")Row 中元素的宽度可以通过 scale 和 min_width 参数的组合来控制,这两个参数都存在于每个组件中。
scale 是一个整数,用于定义元素如何在 Row 中占据空间。如果 scale 设置为 0,则元素不会扩展以占据空间。如果 scale 设置为 1 或更高,则元素会扩展。Row 中的多个元素将与其 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 值,Row 将换行。在文档中了解更多关于 Rows 的信息。
Column 中的组件将垂直堆叠在一起。由于 Blocks 应用的垂直布局本来就是默认布局,因此为了有用,Columns 通常嵌套在 Rows 中。例如
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=300):
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=300):
img1 = gr.Image("images/cheetah.jpg")
btn = gr.Button("Go")
demo.launch()
可以看到第一个列有两个垂直排列的文本框。第二个列有一个图像和按钮,它们是垂直排列的。请注意,两个列的相对宽度由 scale 参数设置。scale 值是两倍的列占据两倍的宽度。
在文档中了解更多关于 Columns 的信息。
要使应用程序占用浏览器全部宽度,通过删除侧边填充,请使用 gr.Blocks(fill_width=True)。
要使顶级组件扩展以占用浏览器全部高度,请使用 fill_height 并为扩展的组件应用 scale。
import gradio as gr
with gr.Blocks(fill_height=True) as demo:
gr.Chatbot(scale=1)
gr.Textbox(scale=0)一些组件支持设置高度和宽度。这些参数接受数字(解释为像素)或字符串。使用字符串可以直接将任何 CSS 单位应用于封装的 Block 元素。
以下是一个说明视口宽度 (vw) 用法的示例
import gradio as gr
with gr.Blocks() as demo:
im = gr.ImageEditor(width="50vw")
demo.launch()您还可以使用 with gr.Tab('tab_name'): 子句创建标签页。在 with gr.Tab('tab_name'): 上下文中创建的任何组件都显示在该标签页中。连续的 Tab 子句被分组在一起,这样一次只能选择一个标签页,并且只有该 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(
0, 1,
value=0.1,
step=0.1,
interactive=True,
label="Slide me",
)
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'): 中定义的任何组件都将在单击手风琴的切换图标时隐藏或显示。
侧边栏是一个可折叠的面板,它将子组件渲染在屏幕左侧,并且可以展开或折叠。
例如
import gradio as gr
import random
def generate_pet_name(animal_type, personality):
cute_prefixes = ["Fluffy", "Ziggy", "Bubbles", "Pickle", "Waffle", "Mochi", "Cookie", "Pepper"]
animal_suffixes = {
"Cat": ["Whiskers", "Paws", "Mittens", "Purrington"],
"Dog": ["Woofles", "Barkington", "Waggins", "Pawsome"],
"Bird": ["Feathers", "Wings", "Chirpy", "Tweets"],
"Rabbit": ["Hops", "Cottontail", "Bouncy", "Fluff"]
}
prefix = random.choice(cute_prefixes)
suffix = random.choice(animal_suffixes[animal_type])
if personality == "Silly":
prefix = random.choice(["Sir", "Lady", "Captain", "Professor"]) + " " + prefix
elif personality == "Royal":
suffix += " the " + random.choice(["Great", "Magnificent", "Wise", "Brave"])
return f"{prefix} {suffix}"
with gr.Blocks() as demo:
with gr.Sidebar(position="left"):
gr.Markdown("# 🐾 Pet Name Generator")
gr.Markdown("Use the options below to generate a unique pet name!")
animal_type = gr.Dropdown(
choices=["Cat", "Dog", "Bird", "Rabbit"],
label="Choose your pet type",
value="Cat"
)
personality = gr.Radio(
choices=["Normal", "Silly", "Royal"],
label="Personality type",
value="Normal"
)
name_output = gr.Textbox(label="Your pet's fancy name:", lines=2)
generate_btn = gr.Button("Generate Name! 🎲", variant="primary")
generate_btn.click(
fn=generate_pet_name,
inputs=[animal_type, personality],
outputs=name_output
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Soft())
在文档中了解更多关于侧边栏的信息。
为了提供一系列有指导意义的有序步骤,一个受控的工作流程,您可以使用 Walkthrough 组件与随附的 Step 组件。
Walkthrough 组件具有为该用例量身定制的视觉风格和用户体验。
编写此组件与 Tab 非常相似,除了应用程序开发人员有责任通过设置父 Walkthrough 的相应 ID 来推进每个步骤,该 ID 应与提供给单个 Step 的 ID 相对应。
在文档中了解更多关于演练的信息。
组件和布局元素都有一个 visible 参数,可以设置初始值,也可以更新。设置 gr.Column(visible=...) 可以在 Column 上用于显示或隐藏一组组件。
import gradio as gr
with gr.Blocks() as demo:
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):
return {
submit_btn: gr.Button(visible=False),
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],
[submit_btn, diagnosis_box, patient_summary_box, output_col],
)
demo.launch()
在某些情况下,您可能希望在实际将组件渲染到 UI 之前定义它们。例如,您可能希望在相应的 gr.Textbox 输入上方显示一个示例部分,使用 gr.Examples。由于 gr.Examples 需要组件对象作为参数,因此您需要先定义输入组件,然后在定义 gr.Examples 对象之后再渲染它。
解决这个问题的方法是在 gr.Blocks() 范围之外定义 gr.Textbox,并在您希望放置它的任何位置使用该组件的 .render() 方法。
这是一个完整的代码示例
input_textbox = gr.Textbox()
with gr.Blocks() as demo:
gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
input_textbox.render()类似地,如果您已经在 Gradio 应用中定义了一个组件,但希望将其取消渲染,以便在应用程序的不同部分进行定义,则可以调用 .unrender() 方法。在以下示例中,Textbox 将出现在第三列中
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
gr.Markdown("Row 1")
textbox = gr.Textbox()
with gr.Column():
gr.Markdown("Row 2")
textbox.unrender()
with gr.Column():
gr.Markdown("Row 3")
textbox.render()
demo.launch()