WebUI可视化:第3章:Gradio入门实战
学习目标
-
✅ 掌握Gradio的安装与基础配置
-
✅ 能创建包含多种交互组件的界面
-
✅ 实现前后端数据交互逻辑
-
✅ 独立开发简单AI应用界面
3.1 Gradio快速安装
3.1.1 通过pip安装
打开终端(Windows:CMD/PowerShell,Mac/Linux:Terminal),执行:
bash
# 基础安装 pip install gradio # 包含额外功能(推荐) pip install "gradio[all]"
3.1.2 验证安装
新建文件 test_install.py
,写入:
python
import gradio as gr print("Gradio版本:", gr.__version__)
运行后看到版本号即成功:
bash
python test_install.py # 输出示例:Gradio版本: 3.36.0
3.2 创建第一个交互界面
3.2.1 基础问候程序
新建 hello_gradio.py
:
python
import gradio as gr def greet(name): return f"你好,{name}!欢迎来到Gradio世界。" # 创建界面 demo = gr.Interface( fn=greet, # 处理函数 inputs=gr.Textbox(label="你的名字"), outputs=gr.Textbox(label="问候语"), title="我的第一个Gradio应用", description="输入名字获取个性化问候" ) demo.launch()
3.2.2 运行与访问
bash
python hello_gradio.py
在浏览器打开 http://localhost:7860
,你会看到:
-
顶部显示标题和描述
-
左侧文本输入框
-
右侧结果显示框
-
底部的"Submit"提