0
点赞
收藏
分享

微信扫一扫

2024下半年,前端的技术风口来了

舟海君 2024-07-30 阅读 13
python

 输出组件的可交互,默认垂直排列

import gradio as gr
def greet(name):
    return "Hello " + name + "!"
with gr.Blocks() as demo:
    name = gr.Textbox(label="Name")
    # 不可交互
    # output = gr.Textbox(label="Output Box")
    # 可交互
    output = gr.Textbox(label="Output", interactive=True) 
    greet_btn = gr.Button("Greet")
    greet_btn.click(fn=greet, inputs=name, outputs=output)
demo.launch()

 

 我们可以为不同的组件设置不同事件,如为输入组件添加change事件。可以进一步查看官方文档,看看组件还有哪些事件

import gradio as gr
def welcome(name):
    return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
    gr.Markdown(
    """
    # Hello World!
    Start typing below to see the output.
    """)
    inp = gr.Textbox(placeholder="What is your name?")
    out = gr.Textbox()
    #设置change事件
    inp.change(fn = welcome, inputs = inp, outputs = out)
demo.launch()

 

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:
    #用markdown语法编辑输出一段话
    gr.Markdown("Flip text or image files using this demo.")
    # 设置tab选项卡
    with gr.Tab("Flip Text"):
        #Blocks特有组件,设置所有子组件按垂直排列
        #垂直排列是默认情况,不加也没关系
        with gr.Column():
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        #Blocks特有组件,设置所有子组件按水平排列
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")
    #设置折叠内容
    with gr.Accordion("Open for More!"):
        gr.Markdown("Look at 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.update修改可见属性

import gradio as gr

def update(name):
    return f"Welcome to Gradio, {name}!", gr.update(interactive=False), gr.update(visible=True)
def clear():
    return "", "", gr.update(interactive=True), gr.update(visible=False)

with gr.Blocks() as demo:
    gr.Markdown("Start typing below and then click **Run** to see the output.")
    with gr.Row():
        inp = gr.Textbox(placeholder="What is your name?")
        out = gr.Textbox()
    btn = gr.Button("Run")
    btn_c = gr.Button("clear", visible=False)
    btn.click(fn=update, inputs=inp, outputs=[out,btn,btn_c])
    btn_c.click(fn=clear, outputs=[inp,out,btn,btn_c])

demo.launch()

举报

相关推荐

0 条评论