gradio 常用函数
package
本文字数:525 字 | 阅读时长 ≈ 2 min

gradio 常用函数

package
本文字数:525 字 | 阅读时长 ≈ 2 min

1. gr.Slider

创建一个 slider bar,即一个可以通过滑动控制的数值

import gradio as gr

def slide(input):
    return input

demo = gr.Interface(
    slide,
    [gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),],
    gr.Number(),
)

if __name__ == "__main__":
    demo.launch()

其中第一和第二个数字分别最大和最小值,value 是默认值,label 是标题,info 是详细信息

2. gr.dropdown

创建一个有下拉菜单的选项卡

import gradio as gr

def drop(animal):
    return animal

demo = gr.Interface(
    drop,
    [gr.Dropdown(["cat", "dog", "bird"], multiselect=False, label="Animal", info="Will add more animals later!"),],
    "text",
)

if __name__ == "__main__":
    demo.launch()

如图,下拉选项可以选择 cat,dog 和 bird,右边输出 str 类型的文本

如果将上面的 multiselect 变为 True,则可以选择多个选项,如下

3. gr.CheckboxGroup

此操作和 dropdown 类似,但是不是下拉菜单了,而是将选项直接展示出来,用户可以根据需要打钩

import gradio as gr


def checkboxgroup(country):
    return country

demo = gr.Interface(
    checkboxgroup,
    [gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),],
    "text",
)

if __name__ == "__main__":
    demo.launch()

此函数不需要定义 multiselect 参数就可以进行多个选择

4. gr.Radio

此函数和上述 checkboxgroup 类似,只不过将打钩变成了点

import gradio as gr


def radio(local_):
    return local_

demo = gr.Interface(
    radio,
    [gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),],
    "text",
)

if __name__ == "__main__":
    demo.launch()

5. update

update 用来更新当前操作(例如文本,图片等),例如根据一些判断来调整文本框的大小

import gradio as gr

def change_textbox(choice):
    if choice == "short":
        return gr.Textbox.update(lines=2, visible=True)
    elif choice == "long":
        return gr.Textbox.update(lines=8, visible=True)
    else:
        return gr.Textbox.update(visible=False)


with gr.Blocks() as demo:
    radio = gr.Radio(["short", "long", "none"], label="What kind of essay would you like to write?")
    text = gr.Textbox(lines=2, interactive=True).style(show_copy_button=True)

    radio.change(fn=change_textbox, inputs=radio, outputs=text)


if __name__ == "__main__":
    demo.launch()

下面根据用户选择,会实时更新文本框的大小

4月 06, 2025
3月 10, 2025
12月 31, 2024