Streamlit 详细使用教程
Streamlit 详细使用教程
Streamlit 是一个用于快速构建和分享数据应用的纯 Python 框架,无需前端知识。以下教程将带你从零开始,逐步掌握 Streamlit 的核心功能与实用技巧。
1. 安装与环境配置
pip install streamlit
验证安装:
streamlit hello
这会启动一个演示应用,访问 http://localhost:8501 查看。
依赖:Python 3.8 – 3.12。
2. 第一个应用
新建 app.py:
import streamlit as st
st.title("我的第一个 Streamlit 应用")
st.write("Hello, Streamlit!")
运行:
streamlit run app.py
每次保存文件后页面自动刷新(热重载)。
3. 文本与数据展示
文本元素
st.title("标题") # 一级标题
st.header("头部") # 二级标题
st.subheader("子标题") # 三级标题
st.markdown("**粗体** 文字") # Markdown 渲染
st.text("纯文本")
st.code("print('hello')", language="python") # 代码块
st.latex(r"e^{i\pi} + 1 = 0") # LaTeX 公式
st.caption("小字说明") # 脚注文字
st.divider() # 分割线
数据展示
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"])
st.dataframe(df) # 交互式表格
st.table(df) # 静态表格
st.json({"key": "value"}) # JSON 展示
st.metric("温度", "25 °C", delta="1.2 °C") # 指标卡片
4. 输入控件
所有控件均返回用户输入值,顶层调用即可。
# 文本输入
name = st.text_input("输入姓名", placeholder="张三")
comment = st.text_area("评论", height=100)
num = st.number_input("年龄", min_value=0, max_value=120, value=25)
# 选择控件
option = st.selectbox("城市", ["北京", "上海", "广州"])
multi = st.multiselect("爱好", ["阅读", "运动", "音乐"], default=["阅读"])
slider_val = st.slider("评分", 0, 10, 5)
is_checked = st.checkbox("我同意条款")
radio_val = st.radio("性别", ["男", "女"], horizontal=True)
# 时间与文件
date = st.date_input("日期")
uploaded_file = st.file_uploader("上传文件", type=["csv", "txt"])
camera = st.camera_input("拍照")
# 按钮与交互
if st.button("点击我"):
st.success("按钮被点击了!")
# 下载按钮
st.download_button("下载数据", data="文件内容", file_name="data.txt")
关键原则:每次交互都会从上到下重新执行整个脚本,Streamlit 通过控件返回的状态更新页面。
5. 布局与容器
将元素组织成视觉块,提升界面结构。
# 侧边栏
with st.sidebar:
st.header("参数设置")
alpha = st.slider("学习率", 0.0, 1.0, 0.01)
# 列布局
col1, col2, col3 = st.columns([2, 1, 1])
col1.metric("销售额", "¥12,000")
col2.metric("成本", "¥8,000")
col3.metric("利润", "¥4,000")
# 容器与空占位
with st.container():
st.write("这是一个容器")
placeholder = st.empty() # 之后可填充或替换
# 展开/折叠
with st.expander("点击查看详情"):
st.write("这里是详细信息")
# 标签页 (tabs)
tab1, tab2 = st.tabs(["图表", "数据"])
tab1.line_chart([1, 2, 3])
tab2.dataframe(df)
6. 图表与可视化
Streamlit 支持多种主流绘图库。
内置图表(基于 Altair)
chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])
st.line_chart(chart_data)
st.area_chart(chart_data)
st.bar_chart(chart_data)
st.scatter_chart(chart_data) # streamlit>=1.25
st.map(pd.DataFrame({"lat": [31.2], "lon": [121.5]})) # 地图
Matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
st.pyplot(fig)
Plotly
import plotly.express as px
fig = px.scatter(x=[1, 2, 3], y=[1, 4, 9])
st.plotly_chart(fig, use_container_width=True)
其他:Bokeh、Altair、PyDeck 等直接使用原生 st.bokeh_chart(), st.altair_chart(), st.pydeck_chart()。
7. 状态与 Session State
Streamlit 默认无状态,每次交互重跑脚本。若需跨交互保存变量,使用 Session State。
# 初始化
if "count" not in st.session_state:
st.session_state.count = 0
if st.button("增加"):
st.session_state.count += 1
st.write("计数:", st.session_state.count)
# 通过回调更新状态
def increment():
st.session_state.count += 1
st.button("回调版增加", on_click=increment)
# 键值对简化写法
st.session_state.key = "value"
常见模式:
- 保存用户登录信息
- 缓存表单数据避免丢失
- 分页计数器
8. 缓存机制
Streamlit 每次交互都重跑全部代码,耗时的数据处理或模型加载应使用缓存装饰器。
@st.cache_data (数据缓存)
用于返回数据对象的函数(DataFrame、列表等)。
@st.cache_data
def load_data(url):
return pd.read_csv(url)
df = load_data("https://example.com/data.csv")
st.dataframe(df)
@st.cache_resource (资源缓存)
用于缓存不可序列化的对象,如数据库连接、机器学习模型。
from transformers import pipeline
@st.cache_resource
def load_model():
return pipeline("sentiment-analysis")
model = load_model()
result = model("I love Streamlit!")
st.write(result)
参数控制:
ttl:缓存生存时间(秒),@st.cache_data(ttl=3600)max_entries:最多缓存条目数show_spinner:加载时显示等待动画
9. 表单与多步交互
当需要批量提交多个输入时,使用表单可避免每次都触发重跑。
with st.form("my_form"):
name = st.text_input("姓名")
age = st.number_input("年龄", 0, 120, 25)
submitted = st.form_submit_button("提交")
if submitted:
st.write(f"你好 {name}, 年龄 {age}")
表单内的所有控件改动不会立即生效,只有在点击提交按钮后才一次性提交。
10. 进度条与状态
import time
# 进度条
progress_bar = st.progress(0)
for i in range(100):
time.sleep(0.01)
progress_bar.progress(i + 1)
# 状态消息
st.success("成功!")
st.info("提示信息")
st.warning("警告")
st.error("错误", icon="🚨")
# 执行时的等待动效
with st.spinner("请等待..."):
time.sleep(2)
st.balloons() # 气球特效
st.snow() # 雪花特效
# 状态元素容器
status = st.status("正在处理...", expanded=True)
status.write("步骤 1 完成")
time.sleep(1)
status.write("步骤 2 完成")
status.update(label="处理完毕", state="complete")
11. 主题与自定义
在 .streamlit/config.toml 文件中自定义主题:
[theme]
primaryColor = "#F63366"
backgroundColor = "#FFFFFF"
secondaryBackgroundColor = "#F0F2F6"
textColor = "#262730"
font = "sans serif"
或通过界面右上角菜单 → Settings → Theme 实时修改。
自定义 CSS(谨慎使用):
st.markdown("""
<style>
div.stButton > button {
background-color: #4CAF50;
color: white;
}
</style>
""", unsafe_allow_html=True)
12. 页面与多页面应用
单文件多页面(推荐)
创建 pages/ 文件夹,放入 Python 文件即自动识别为多个页面:
my_app/
├── main.py # 主页
└── pages/
├── 1_数据探索.py
└── 2_模型训练.py
页面文件名排序决定侧边栏导航顺序。
页面配置
在主脚本开头使用:
st.set_page_config(
page_title="我的应用",
page_icon="📊",
layout="wide", # 或 "centered"
initial_sidebar_state="expanded"
)
13. 媒体与文件
st.image("cat.jpg", caption="可爱的猫", width=300)
st.audio("song.mp3")
st.video("movie.mp4")
14. 部署应用
Streamlit Community Cloud(免费)
- 将代码推送到公开 GitHub 仓库。
- 在 share.streamlit.io 用 GitHub 登录。
- 点击 "New app",选择仓库、分支和主文件路径,点击 Deploy。
其他平台
可使用 Docker 部署,例:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
也可部署到 Hugging Face Spaces、Railway、Heroku 等。
15. 实用技巧
动态改变控件
通过 st.session_state 和占位符控制控件状态:
if st.checkbox("显示输入框"):
user_input = st.text_input("输入内容")
else:
st.empty() # 隐藏输入框区域
查询参数
使用 st.query_params 读取 URL 参数:
params = st.query_params
st.write(params.get("user", "默认用户"))
处理大数据
- 使用
@st.cache_data缓存数据加载。 - 使用
st.dataframe自动分页显示大数据集。 - 利用
st.connection直连数据库(实验性功能)。
安全性
- 避免在
st.text_input等控件中直接执行用户输入的代码(如eval)。 - 在生产环境配置 secrets:
.streamlit/secrets.toml存储密钥,通过st.secrets["key"]访问。
16. 完整示例:交互式数据探索工具
import streamlit as st
import pandas as pd
import plotly.express as px
st.set_page_config(page_title="数据探索", layout="wide")
st.title("📊 数据探索仪表板")
# 侧边栏设置
with st.sidebar:
uploaded = st.file_uploader("上传 CSV", type="csv")
if uploaded:
df = pd.read_csv(uploaded)
numeric_cols = df.select_dtypes("number").columns.tolist()
x_axis = st.selectbox("X 轴", numeric_cols)
y_axis = st.selectbox("Y 轴", numeric_cols)
color_col = st.selectbox("颜色分组", df.columns)
# 主区域
if uploaded:
col1, col2 = st.columns(2)
col1.metric("行数", df.shape[0])
col2.metric("列数", df.shape[1])
st.subheader("散点图")
fig = px.scatter(df, x=x_axis, y=y_axis, color=color_col)
st.plotly_chart(fig, use_container_width=True)
st.subheader("原始数据")
st.dataframe(df.head(100))
else:
st.info("请在侧边栏上传 CSV 文件")
总结
Streamlit 的精髓在于以脚本方式编写应用,将 Python 数据生态与前端无缝衔接。掌握上述内容,你已能构建从数据处理、可视化到模型演示的全功能应用。遇到更多细节可直接查阅官方文档,那里有最新的 API 参考和社区扩展。

浙公网安备 33010602011771号