streamlit by silvainfm/claude-skills
npx skills add https://github.com/silvainfm/claude-skills --skill streamlitStreamlit 是一个 Python 框架,用于快速构建和部署用于数据科学和机器学习的交互式 Web 应用程序。仅使用 Python 即可创建精美的 Web 应用——无需前端开发经验。当代码更改时,应用程序会自动实时更新。
当用户出现以下情况时激活此技能:
检查是否已安装 Streamlit:
python3 -c "import streamlit; print(streamlit.__version__)"
如果未安装:
pip3 install streamlit
创建并运行您的第一个应用:
# 创建包含 Streamlit 代码的 app.py 文件
streamlit run app.py
应用会自动在您的浏览器中打开,地址为 http://localhost:8501
每个 Streamlit 应用都遵循这个简单的模式:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
import streamlit as st
# 设置页面配置(必须是第一个 Streamlit 命令)
st.set_page_config(
page_title="我的应用",
page_icon="📊",
layout="wide"
)
# 标题和描述
st.title("我的数据应用")
st.write("欢迎来到我的交互式仪表板!")
# 您的应用代码放在这里
# 当小部件发生变化时,Streamlit 会自动从上到下重新运行
import streamlit as st, pandas as pd
# 文本元素
st.title("主标题")
st.header("章节标题")
st.subheader("子章节标题")
st.text("等宽文本")
st.markdown("**粗体** 和 *斜体* 文本")
st.caption("小号说明文字")
# 代码块
st.code("""
def hello():
print("Hello, World!")
""", language="python")
# 显示数据
df = pd.DataFrame({
'列 A': [1, 2, 3],
'列 B': [4, 5, 6]
})
st.dataframe(df) # 交互式表格
st.table(df) # 静态表格
st.json({'key': 'value'}) # JSON 数据
# 指标
st.metric(
label="收入",
value="$1,234",
delta="12%"
)
import streamlit as st
# 文本输入
name = st.text_input("输入您的姓名")
email = st.text_input("邮箱", type="default")
password = st.text_input("密码", type="password")
text = st.text_area("长文本", height=100)
# 数字
age = st.number_input("年龄", min_value=0, max_value=120, value=25)
slider_val = st.slider("选择一个值", 0, 100, 50)
range_val = st.slider("选择范围", 0, 100, (25, 75))
# 选择
option = st.selectbox("选择一个", ["选项 1", "选项 2", "选项 3"])
options = st.multiselect("选择多个", ["A", "B", "C", "D"])
radio = st.radio("选择一个", ["是", "否", "可能"])
# 复选框
agree = st.checkbox("我同意条款")
show_data = st.checkbox("显示原始数据")
# 按钮
if st.button("点击我"):
st.write("按钮被点击了!")
# 日期和时间
date = st.date_input("选择日期")
time = st.time_input("选择时间")
# 文件上传
uploaded_file = st.file_uploader("选择一个文件", type=['csv', 'xlsx', 'txt'])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.dataframe(df)
# 下载按钮
st.download_button(
label="下载数据",
data=df.to_csv(index=False),
file_name="data.csv",
mime="text/csv"
)
import streamlit as st
import pandas as pd, numpy as np, matplotlib.pyplot as plt
import plotly.express as px
# 示例数据
df = pd.DataFrame({
'x': range(10),
'y': np.random.randn(10)
})
# Streamlit 原生图表
st.line_chart(df)
st.area_chart(df)
st.bar_chart(df)
# 使用地图数据的散点图
map_data = pd.DataFrame(
np.random.randn(100, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon']
)
st.map(map_data)
# Matplotlib
fig, ax = plt.subplots()
ax.plot(df['x'], df['y'])
ax.set_title("Matplotlib 图表")
st.pyplot(fig)
# Plotly(交互式)
fig = px.scatter(df, x='x', y='y', title="交互式 Plotly 图表")
st.plotly_chart(fig, use_container_width=True)
# 也支持 Altair、Bokeh 和其他库
import streamlit as st
# 列
col1, col2, col3 = st.columns(3)
with col1:
st.header("列 1")
st.write("内容在这里")
with col2:
st.header("列 2")
st.write("更多内容")
with col3:
st.header("列 3")
st.write("还有更多")
# 标签页
tab1, tab2, tab3 = st.tabs(["概览", "数据", "设置"])
with tab1:
st.write("概览内容")
with tab2:
st.write("数据内容")
with tab3:
st.write("设置内容")
# 扩展器(可折叠部分)
with st.expander("点击展开"):
st.write("可以展开的隐藏内容")
# 容器
with st.container():
st.write("这是在容器内部")
st.write("另一行")
# 侧边栏
st.sidebar.title("侧边栏")
st.sidebar.selectbox("选择选项", ["A", "B", "C"])
st.sidebar.slider("侧边栏滑块", 0, 100)
import streamlit as st, time
# 成功、信息、警告、错误消息
st.success("成功!一切正常。")
st.info("这是一条信息消息。")
st.warning("这是一个警告。")
st.error("这是一条错误消息。")
# 进度条
progress_bar = st.progress(0)
for i in range(100):
time.sleep(0.01)
progress_bar.progress(i + 1)
# 旋转器(加载指示器)
with st.spinner("处理中..."):
time.sleep(3)
st.success("完成!")
# 气球(庆祝)
st.balloons()
# 雪花(庆祝)
# st.snow()
import streamlit as st, pandas as pd, time
# 缓存数据加载(在多次重新运行之间保持)
@st.cache_data
def load_data():
time.sleep(2) # 模拟缓慢的数据加载
return pd.read_csv('large_file.csv')
# 缓存资源(连接、模型)
@st.cache_resource
def load_model():
# 加载 ML 模型(昂贵操作)
return load_my_model()
# 使用缓存数据
df = load_data() # 仅加载一次,然后缓存
model = load_model() # 全局缓存
st.write(f"已加载 {len(df)} 行")
import streamlit as st
# 初始化会话状态
if 'count' not in st.session_state:
st.session_state.count = 0
# 增加计数器
if st.button("增加"):
st.session_state.count += 1
st.write(f"计数:{st.session_state.count}")
# 在多次重新运行之间存储用户数据
if 'user_data' not in st.session_state:
st.session_state.user_data = {}
name = st.text_input("姓名")
if name:
st.session_state.user_data['name'] = name
st.write(f"你好,{st.session_state.user_data['name']}!")
import streamlit as st, pandas as pd, plotly.express as px
st.set_page_config(page_title="销售仪表板", layout="wide")
# 侧边栏过滤器
st.sidebar.header("过滤器")
date_range = st.sidebar.date_input("日期范围", [])
category = st.sidebar.multiselect("类别", ["A", "B", "C"])
# 加载数据
@st.cache_data
def load_sales_data():
return pd.read_csv('sales_data.csv')
df = load_sales_data()
# 应用过滤器
if date_range:
df = df[df['date'].between(date_range[0], date_range[1])]
if category:
df = df[df['category'].isin(category)]
# 指标行
col1, col2, col3, col4 = st.columns(4)
col1.metric("总收入", f"${df['revenue'].sum():,.0f}")
col2.metric("订单数", f"{len(df):,}")
col3.metric("平均订单", f"${df['revenue'].mean():.2f}")
col4.metric("热门产品", df['product'].mode()[0])
# 图表
col1, col2 = st.columns(2)
with col1:
st.subheader("按类别划分的收入")
fig = px.bar(df.groupby('category')['revenue'].sum().reset_index(),
x='category', y='revenue')
st.plotly_chart(fig, use_container_width=True)
with col2:
st.subheader("收入趋势")
fig = px.line(df.groupby('date')['revenue'].sum().reset_index(),
x='date', y='revenue')
st.plotly_chart(fig, use_container_width=True)
# 数据表格
with st.expander("查看原始数据"):
st.dataframe(df)
import streamlit as st, pandas as pd, plotly.express as px
st.title("📊 数据探索器")
# 文件上传
uploaded_file = st.file_uploader("上传 CSV", type=['csv'])
if uploaded_file:
df = pd.read_csv(uploaded_file)
# 显示基本信息
st.subheader("数据集概览")
col1, col2, col3 = st.columns(3)
col1.metric("行数", len(df))
col2.metric("列数", len(df.columns))
col3.metric("内存占用", f"{df.memory_usage(deep=True).sum() / 1024**2:.2f} MB")
# 列选择
st.subheader("探索数据")
columns = st.multiselect("选择列", df.columns.tolist(), default=df.columns.tolist()[:5])
if columns:
st.dataframe(df[columns])
# 统计信息
st.subheader("统计信息")
st.write(df[columns].describe())
# 可视化
st.subheader("可视化")
col1, col2 = st.columns(2)
with col1:
x_col = st.selectbox("X 轴", columns)
with col2:
y_col = st.selectbox("Y 轴", columns)
chart_type = st.radio("图表类型", ["散点图", "折线图", "柱状图"])
if chart_type == "散点图":
fig = px.scatter(df, x=x_col, y=y_col)
elif chart_type == "折线图":
fig = px.line(df, x=x_col, y=y_col)
else:
fig = px.bar(df, x=x_col, y=y_col)
st.plotly_chart(fig, use_container_width=True)
使用以下文件结构创建多页面应用:
app/
├── main.py
└── pages/
├── 1_📊_Dashboard.py
├── 2_📈_Analytics.py
└── 3_⚙️_Settings.py
主页面 (main.py):
import streamlit as st
st.set_page_config(page_title="多页面应用", page_icon="🏠")
st.title("欢迎使用我的应用")
st.sidebar.success("在上方选择一个页面。")
st.markdown("""
这是主页。使用侧边栏进行导航。
""")
页面会自动出现在侧边栏中。每个页面都是一个单独的 Python 文件。
import streamlit as st
# 表单可以防止每次小部件更改时重新运行
with st.form("my_form"):
st.write("填写表单")
name = st.text_input("姓名")
age = st.number_input("年龄", min_value=0, max_value=120)
favorite_color = st.selectbox("最喜欢的颜色", ["红色", "绿色", "蓝色"])
# 表单提交按钮
submitted = st.form_submit_button("提交")
if submitted:
st.write(f"姓名:{name}")
st.write(f"年龄:{age}")
st.write(f"颜色:{favorite_color}")
@st.cache_data 和 @st.cache_resource 缓存昂贵操作st.session_state 在多次重新运行之间保持数据st.set_page_config(layout="wide")使用 st.form() 批量处理输入或使用 st.session_state 控制行为。
缓存昂贵操作:
@st.cache_data
def expensive_computation(param):
# 您的代码在这里
return result
使用会话状态:
if 'my_var' not in st.session_state:
st.session_state.my_var = initial_value
每周安装次数
140
代码仓库
GitHub 星标数
2
首次出现
2026 年 1 月 23 日
安全审计
安装于
opencode124
gemini-cli117
codex113
cursor108
github-copilot102
kimi-cli86
Streamlit is a Python framework for rapidly building and deploying interactive web applications for data science and machine learning. Create beautiful web apps with just Python - no frontend development experience required. Apps automatically update in real-time as code changes.
Activate when the user:
Check if Streamlit is installed:
python3 -c "import streamlit; print(streamlit.__version__)"
If not installed:
pip3 install streamlit
Create and run your first app:
# Create app.py with Streamlit code
streamlit run app.py
The app opens automatically in your browser at http://localhost:8501
Every Streamlit app follows this simple pattern:
import streamlit as st
# Set page configuration (must be first Streamlit command)
st.set_page_config(
page_title="My App",
page_icon="📊",
layout="wide"
)
# Title and description
st.title("My Data App")
st.write("Welcome to my interactive dashboard!")
# Your app code here
# Streamlit automatically reruns from top to bottom when widgets change
import streamlit as st, pandas as pd
# Text elements
st.title("Main Title")
st.header("Section Header")
st.subheader("Subsection Header")
st.text("Fixed-width text")
st.markdown("**Bold** and *italic* text")
st.caption("Small caption text")
# Code blocks
st.code("""
def hello():
print("Hello, World!")
""", language="python")
# Display data
df = pd.DataFrame({
'Column A': [1, 2, 3],
'Column B': [4, 5, 6]
})
st.dataframe(df) # Interactive table
st.table(df) # Static table
st.json({'key': 'value'}) # JSON data
# Metrics
st.metric(
label="Revenue",
value="$1,234",
delta="12%"
)
import streamlit as st
# Text input
name = st.text_input("Enter your name")
email = st.text_input("Email", type="default")
password = st.text_input("Password", type="password")
text = st.text_area("Long text", height=100)
# Numbers
age = st.number_input("Age", min_value=0, max_value=120, value=25)
slider_val = st.slider("Select a value", 0, 100, 50)
range_val = st.slider("Select range", 0, 100, (25, 75))
# Selections
option = st.selectbox("Choose one", ["Option 1", "Option 2", "Option 3"])
options = st.multiselect("Choose multiple", ["A", "B", "C", "D"])
radio = st.radio("Pick one", ["Yes", "No", "Maybe"])
# Checkboxes
agree = st.checkbox("I agree to terms")
show_data = st.checkbox("Show raw data")
# Buttons
if st.button("Click me"):
st.write("Button clicked!")
# Date and time
date = st.date_input("Select date")
time = st.time_input("Select time")
# File upload
uploaded_file = st.file_uploader("Choose a file", type=['csv', 'xlsx', 'txt'])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.dataframe(df)
# Download button
st.download_button(
label="Download data",
data=df.to_csv(index=False),
file_name="data.csv",
mime="text/csv"
)
import streamlit as st
import pandas as pd, numpy as np, matplotlib.pyplot as plt
import plotly.express as px
# Sample data
df = pd.DataFrame({
'x': range(10),
'y': np.random.randn(10)
})
# Streamlit native charts
st.line_chart(df)
st.area_chart(df)
st.bar_chart(df)
# Scatter plot with map data
map_data = pd.DataFrame(
np.random.randn(100, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon']
)
st.map(map_data)
# Matplotlib
fig, ax = plt.subplots()
ax.plot(df['x'], df['y'])
ax.set_title("Matplotlib Chart")
st.pyplot(fig)
# Plotly (interactive)
fig = px.scatter(df, x='x', y='y', title="Interactive Plotly Chart")
st.plotly_chart(fig, use_container_width=True)
# Altair, Bokeh, and other libraries also supported
import streamlit as st
# Columns
col1, col2, col3 = st.columns(3)
with col1:
st.header("Column 1")
st.write("Content here")
with col2:
st.header("Column 2")
st.write("More content")
with col3:
st.header("Column 3")
st.write("Even more")
# Tabs
tab1, tab2, tab3 = st.tabs(["Overview", "Data", "Settings"])
with tab1:
st.write("Overview content")
with tab2:
st.write("Data content")
with tab3:
st.write("Settings content")
# Expander (collapsible section)
with st.expander("Click to expand"):
st.write("Hidden content that can be expanded")
# Container
with st.container():
st.write("This is inside a container")
st.write("Another line")
# Sidebar
st.sidebar.title("Sidebar")
st.sidebar.selectbox("Choose option", ["A", "B", "C"])
st.sidebar.slider("Sidebar slider", 0, 100)
import streamlit as st, time
# Success, info, warning, error messages
st.success("Success! Everything worked.")
st.info("This is an informational message.")
st.warning("This is a warning.")
st.error("This is an error message.")
# Progress bar
progress_bar = st.progress(0)
for i in range(100):
time.sleep(0.01)
progress_bar.progress(i + 1)
# Spinner (loading indicator)
with st.spinner("Processing..."):
time.sleep(3)
st.success("Done!")
# Balloons (celebration)
st.balloons()
# Snow (celebration)
# st.snow()
import streamlit as st, pandas as pd, time
# Cache data loading (persists across reruns)
@st.cache_data
def load_data():
time.sleep(2) # Simulate slow data load
return pd.read_csv('large_file.csv')
# Cache resource (connections, models)
@st.cache_resource
def load_model():
# Load ML model (expensive operation)
return load_my_model()
# Use cached data
df = load_data() # Only loads once, then cached
model = load_model() # Cached globally
st.write(f"Loaded {len(df)} rows")
import streamlit as st
# Initialize session state
if 'count' not in st.session_state:
st.session_state.count = 0
# Increment counter
if st.button("Increment"):
st.session_state.count += 1
st.write(f"Count: {st.session_state.count}")
# Store user data across reruns
if 'user_data' not in st.session_state:
st.session_state.user_data = {}
name = st.text_input("Name")
if name:
st.session_state.user_data['name'] = name
st.write(f"Hello, {st.session_state.user_data['name']}!")
import streamlit as st, pandas as pd, plotly.express as px
st.set_page_config(page_title="Sales Dashboard", layout="wide")
# Sidebar filters
st.sidebar.header("Filters")
date_range = st.sidebar.date_input("Date Range", [])
category = st.sidebar.multiselect("Category", ["A", "B", "C"])
# Load data
@st.cache_data
def load_sales_data():
return pd.read_csv('sales_data.csv')
df = load_sales_data()
# Apply filters
if date_range:
df = df[df['date'].between(date_range[0], date_range[1])]
if category:
df = df[df['category'].isin(category)]
# Metrics row
col1, col2, col3, col4 = st.columns(4)
col1.metric("Total Revenue", f"${df['revenue'].sum():,.0f}")
col2.metric("Orders", f"{len(df):,}")
col3.metric("Avg Order", f"${df['revenue'].mean():.2f}")
col4.metric("Top Product", df['product'].mode()[0])
# Charts
col1, col2 = st.columns(2)
with col1:
st.subheader("Revenue by Category")
fig = px.bar(df.groupby('category')['revenue'].sum().reset_index(),
x='category', y='revenue')
st.plotly_chart(fig, use_container_width=True)
with col2:
st.subheader("Revenue Trend")
fig = px.line(df.groupby('date')['revenue'].sum().reset_index(),
x='date', y='revenue')
st.plotly_chart(fig, use_container_width=True)
# Data table
with st.expander("View Raw Data"):
st.dataframe(df)
import streamlit as st, pandas as pd, plotly.express as px
st.title("📊 Data Explorer")
# File upload
uploaded_file = st.file_uploader("Upload CSV", type=['csv'])
if uploaded_file:
df = pd.read_csv(uploaded_file)
# Show basic info
st.subheader("Dataset Overview")
col1, col2, col3 = st.columns(3)
col1.metric("Rows", len(df))
col2.metric("Columns", len(df.columns))
col3.metric("Memory", f"{df.memory_usage(deep=True).sum() / 1024**2:.2f} MB")
# Column selection
st.subheader("Explore Data")
columns = st.multiselect("Select columns", df.columns.tolist(), default=df.columns.tolist()[:5])
if columns:
st.dataframe(df[columns])
# Statistics
st.subheader("Statistics")
st.write(df[columns].describe())
# Visualization
st.subheader("Visualize")
col1, col2 = st.columns(2)
with col1:
x_col = st.selectbox("X-axis", columns)
with col2:
y_col = st.selectbox("Y-axis", columns)
chart_type = st.radio("Chart Type", ["Scatter", "Line", "Bar"])
if chart_type == "Scatter":
fig = px.scatter(df, x=x_col, y=y_col)
elif chart_type == "Line":
fig = px.line(df, x=x_col, y=y_col)
else:
fig = px.bar(df, x=x_col, y=y_col)
st.plotly_chart(fig, use_container_width=True)
Create a multi-page app with file structure:
app/
├── main.py
└── pages/
├── 1_📊_Dashboard.py
├── 2_📈_Analytics.py
└── 3_⚙️_Settings.py
Main page (main.py):
import streamlit as st
st.set_page_config(page_title="Multi-Page App", page_icon="🏠")
st.title("Welcome to My App")
st.sidebar.success("Select a page above.")
st.markdown("""
This is the home page. Navigate using the sidebar.
""")
Pages automatically appear in the sidebar. Each page is a separate Python file.
import streamlit as st
# Forms prevent rerun on every widget change
with st.form("my_form"):
st.write("Fill out the form")
name = st.text_input("Name")
age = st.number_input("Age", min_value=0, max_value=120)
favorite_color = st.selectbox("Favorite Color", ["Red", "Green", "Blue"])
# Form submit button
submitted = st.form_submit_button("Submit")
if submitted:
st.write(f"Name: {name}")
st.write(f"Age: {age}")
st.write(f"Color: {favorite_color}")
@st.cache_data and @st.cache_resourcest.session_state to persist data across rerunsst.set_page_config(layout="wide") for dashboardsUse st.form() to batch inputs or st.session_state to control behavior.
Cache expensive operations:
@st.cache_data
def expensive_computation(param):
# Your code here
return result
Use session state:
if 'my_var' not in st.session_state:
st.session_state.my_var = initial_value
Weekly Installs
140
Repository
GitHub Stars
2
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode124
gemini-cli117
codex113
cursor108
github-copilot102
kimi-cli86
超能力技能使用指南:AI助手技能调用优先级与工作流程详解
50,500 周安装