文章目录
快速参考
https://docs.streamlit.io/develop/quick-reference
- 速查表
一份包含 Streamlit 命令及示例语法的密集列表。
https://docs.streamlit.io/develop/quick-reference/cheat-sheet - 版本说明
了解 Streamlit 每个新版本的更新内容。
https://docs.streamlit.io/develop/quick-reference/release-notes - 预发布功能
了解我们如何引入新功能,以及您如何能抢先体验它们!
https://docs.streamlit.io/develop/quick-reference/prerelease - 路线图
抢先了解我们未来一年的规划。
https://roadmap.streamlit.app/
Streamlit API 速查表
https://docs.streamlit.io/develop/quick-reference/cheat-sheet
本文档是 Streamlit 最新版本 v1.47.0 的官方文档摘要。
安装与导入
pip install streamlit
streamlit run first_app.py
导入规范
import streamlit as st
预发布功能
pip uninstall streamlit
pip install streamlit-nightly --upgrade
了解更多关于实验性功能的信息
命令行
streamlit cache clear
streamlit config show
streamlit docs
streamlit hello
streamlit help
streamlit init
streamlit run streamlit_app.py
streamlit version
魔法命令
# Magic commands implicitly
# call st.write().
"_This_ is some **Markdown**"
my_variable
"dataframe:", my_data_frame
显示文本
st.write("Most objects") # df, err, func, keras!
st.write(["st", "is <", 3])
st.write_stream(my_generator)
st.write_stream(my_llm_stream)
st.text("Fixed width text")
st.markdown("_Markdown_")
st.latex(r""" e^{i\pi} + 1 = 0 """)
st.title("My title")
st.header("My header")
st.subheader("My sub")
st.code("for i in range(8): foo()")
st.badge("New")
st.html("<p>Hi!</p>")
显示数据
st.dataframe(my_dataframe)
st.table(data.iloc[0:10])
st.json({"foo":"bar","fu":"ba"})
st.metric("My metric", 42, 2)
显示媒体
st.image("./header.png")
st.audio(data)
st.video(data)
st.video(data, subtitles="./subs.vtt")
st.logo("logo.jpg")
显示图表
st.area_chart(df)
st.bar_chart(df)
st.bar_chart(df, horizontal=True)
st.line_chart(df)
st.map(df)
st.scatter_chart(df)
st.altair_chart(chart)
st.bokeh_chart(fig)
st.graphviz_chart(fig)
st.plotly_chart(fig)
st.pydeck_chart(chart)
st.pyplot(fig)
st.vega_lite_chart(df, spec)
# Work with user selections
event = st.plotly_chart(
df,
on_select="rerun"
)
event = st.altair_chart(
chart,
on_select="rerun"
)
event = st.vega_lite_chart(
df,
spec,
on_select="rerun"
)
要使用更新版本的 Bokeh,请参阅我们的自定义组件 streamlit-bokeh
。
向侧边栏添加元素
# Just add it after st.sidebar:
a = st.sidebar.radio("Select one:", [1, 2])
# Or use "with" notation:
with st.sidebar:
st.radio("Select one:", [1, 2])
列
# Two equal columns:
col1, col2 = st.columns(2)
col1.write("This is column 1")
col2.write("This is column 2")
# Three different columns:
col1, col2, col3 = st.columns([3, 1, 1])
# col1 is larger.
# Bottom-aligned columns
col1, col2 = st.columns(2, vertical_alignment="bottom")
# You can also use "with" notation:
with col1:
st.radio("Select one:", [1, 2])
Tabs
# Insert containers separated into tabs:
tab1, tab2 = st.tabs(["Tab 1", "Tab2"])
tab1.write("this is tab 1")
tab2.write("this is tab 2")
# You can also use "with" notation:
with tab1:
st.radio("Select one:", [1, 2])
可扩展容器
expand = st.expander("My label", icon=":material/info:")
expand.write("Inside the expander.")
pop = st.popover("Button label")
pop.checkbox("Show all")
# You can also use "with" notation:
with expand:
st.radio("Select one:", [1, 2])
控制流程
# Stop execution immediately:
st.stop()
# Rerun script immediately:
st.rerun()
# Navigate to another page:
st.switch_page("pages/my_page.py")
# Define a navigation widget in your entrypoint file
pg = st.navigation(
st.Page("page1.py", title="Home", url_path="home", default=True)
st.Page("page2.py", title="Preferences", url_path="settings")
)
pg.run()
# Group multiple widgets:
with st.form(key="my_form"):
username = st.text_input("Username")
password = st.text_input("Password")
st.form_submit_button("Login")
# Define a dialog function
@st.dialog("Welcome!")
def modal_dialog():
st.write("Hello")
modal_dialog()
# Define a fragment
@st.fragment
def fragment_function():
df = get_data()
st.line_chart(df)
st.button("Update")
fragment_function()
显示交互式小部件
st.button("Click me")
st.download_button("Download file", data)
st.link_button("Go to gallery", url)
st.page_link("app.py", label="Home")
st.data_editor("Edit data", data)
st.checkbox("I agree")
st.feedback("thumbs")
st.pills("Tags", ["Sports", "Politics"])
st.radio("Pick one", ["cats", "dogs"])
st.segmented_control("Filter", ["Open", "Closed"])
st.toggle("Enable")
st.selectbox("Pick one", ["cats", "dogs"])
st.multiselect("Buy", ["milk", "apples", "potatoes"])
st.slider("Pick a number", 0, 100)
st.select_slider("Pick a size", ["S", "M", "L"])
st.text_input("First name")
st.number_input("Pick a number", 0, 10)
st.text_area("Text to translate")
st.date_input("Your birthday")
st.time_input("Meeting time")
st.file_uploader("Upload a CSV")
st.audio_input("Record a voice message")
st.camera_input("Take a picture")
st.color_picker("Pick a color")
# Use widgets' returned values in variables:
for i in range(int(st.number_input("Num:"))):
foo()
if st.sidebar.selectbox("I:",["f"]) == "f":
b()
my_slider_val = st.slider("Quinn Mallory", 1, 88)
st.write(slider_val)
# Disable widgets to remove interactivity:
st.slider("Pick a number", 0, 100, disabled=True)
构建基于聊天的应用程序
# Insert a chat message container.
with st.chat_message("user"):
st.write("Hello 👋")
st.line_chart(np.random.randn(30, 3))
# Display a chat input widget at the bottom of the app.
st.chat_input("Say something")
# Display a chat input widget inline.
with st.container():
st.chat_input("Say something")
了解如何构建基础LLM聊天应用
数据变更
# Add rows to a dataframe after
# showing it.
element = st.dataframe(df1)
element.add_rows(df2)
# Add rows to a chart after
# showing it.
element = st.line_chart(df1)
element.add_rows(df2)
显示代码
with st.echo():
st.write("Code will be executed and printed")
占位符、帮助与选项
# Replace any single element.
element = st.empty()
element.line_chart(...)
element.text_input(...) # Replaces previous.
# Insert out of order.
elements = st.container()
elements.line_chart(...)
st.write("Hello")
elements.text_input(...) # Appears above "Hello".
st.help(pandas.DataFrame)
st.get_option(key)
st.set_option(key, value)
st.set_page_config(layout="wide")
st.query_params[key]
st.query_params.from_dict(params_dict)
st.query_params.get_all(key)
st.query_params.clear()
st.html("<p>Hi!</p>")
连接数据源
st.connection("pets_db", type="sql")
conn = st.connection("sql")
conn = st.connection("snowflake")
class MyConnection(BaseConnection[myconn.MyConnection]):
def _connect(self, **kwargs) -> MyConnection:
return myconn.connect(**self._secrets, **kwargs)
def query(self, query):
return self._instance.query(query)
优化性能
缓存数据对象
# E.g. Dataframe computation, storing downloaded data, etc.
@st.cache_data
def foo(bar):
# Do something expensive and return data
return data
# Executes foo
d1 = foo(ref1)
# Does not execute foo
# Returns cached item by value, d1 == d2
d2 = foo(ref1)
# Different arg, so function foo executes
d3 = foo(ref2)
# Clear the cached value for foo(ref1)
foo.clear(ref1)
# Clear all cached entries for this function
foo.clear()
# Clear values from *all* in-memory or on-disk cached functions
st.cache_data.clear()
缓存全局资源
# E.g. TensorFlow session, database connection, etc.
@st.cache_resource
def foo(bar):
# Create and return a non-data object
return session
# Executes foo
s1 = foo(ref1)
# Does not execute foo
# Returns cached item by reference, s1 == s2
s2 = foo(ref1)
# Different arg, so function foo executes
s3 = foo(ref2)
# Clear the cached value for foo(ref1)
foo.clear(ref1)
# Clear all cached entries for this function
foo.clear()
# Clear all global resources from cache
st.cache_resource.clear()
显示进度和状态
# Show a spinner during a process
with st.spinner(text="In progress"):
time.sleep(3)
st.success("Done")
# Show and update progress bar
bar = st.progress(50)
time.sleep(3)
bar.progress(100)
with st.status("Authenticating...") as s:
time.sleep(2)
st.write("Some long response.")
s.update(label="Response")
st.balloons()
st.snow()
st.toast("Warming up...")
st.error("Error message")
st.warning("Warning message")
st.info("Info message")
st.success("Success message")
st.exception(e)
为用户个性化定制应用
# Authenticate users
if not st.user.is_logged_in:
st.login("my_provider")
f"Hi, {st.user.name}"
st.logout()
# Get dictionaries of cookies, headers, locale, and browser data
st.context.cookies
st.context.headers
st.context.ip_address
st.context.is_embedded
st.context.locale
st.context.theme.type
st.context.timezone
st.context.timezone_offset
st.context.url
版本发布说明
https://docs.streamlit.io/develop/quick-reference/release-notes
本文档列出了 Streamlit 最新版本的主要更新、错误修复和已知问题。如需了解夜间构建版本或实验性功能的信息,请参阅预发布功能。
升级 Streamlit
提示
要升级到最新版本的 Streamlit,请运行:
pip install --upgrade streamlit
版本 1.47.0(最新版)
发布日期:2025年7月16日
亮点功能
- 🎨 Streamlit 新增了主题配置选项!
theme.baseFontWeight
:设置应用中文本的基础字体粗细。theme.chartCategoricalColors
:为 Plotly、Altair 和 Vega-Lite 图表配置默认分类颜色。theme.chartSequentialColors
:为 Plotly、Altair 和 Vega-Lite 图表配置默认顺序颜色。theme.codeFontWeight
:设置代码文本的字体粗细。theme.dataframeHeaderBackgroundColor
:设置数据框表头的背景颜色。theme.headingFontSizes
:设置标题的字体大小。theme.headingFontWeights
:设置标题的字体粗细。theme.linkUnderline
:配置是否显示链接下划线。
重要变更
- 💬 现在可以通过 Session State 设置
st.chat_input
的未提交值(#10175, #7166)。 - ↔️ 可以为
st.html
、st.feedback
、st.pills
、st.segmented_control
和st.multiselect
设置width
参数。 - ↕️ 可以为
st.metric
和st.text_area
设置height
参数。 - 👩💻
st.code
和st.form
现在支持height="stretch"
。 - 🧑💻
st.code
现在支持width="content"
。 - ⏱️ 现在可以通过
show_time
参数在缓存函数的 spinner 中显示耗时(#11469, #10647)。感谢 Darkace01! server.showEmailPrompt
允许配置是否显示电子邮件提示(针对本地运行的应用程序)。- 💾
NumberColumn
和ProgressColumn
支持"bytes"
作为预定义格式(#11288, #11287)。感谢 cgivre! - ⚙️ 列配置现在支持以像素为单位设置列宽(#11838)。
- ℹ️
LinkColumn
的display_text
参数现在支持 Material 图标(#11690, #7004)。 - 🖊️
st.dialog
的title
参数现在支持 Markdown(#11763, #11755)。 - 🧩 为了支持代理自定义组件的请求,在
declare_component
中可以同时设置url
和path
(#11698)。
其他变更
- 🧭 侧边栏导航部件中的部分标签现在可折叠(#11863)。
- 📂 当应用界面中显示“文件更改”通知时,“部署”按钮会被隐藏(#11834)。
- 🔝 当应用使用顶部导航时,标题栏增加了更多内边距(#11836)。
- 🪜 在
NumberColumn
中,step
的精度会覆盖format
的显示精度,除非format
是 printf 字符串(#11835)。 - 📅 当
st.date_input
接受日期范围时,部件会在日历下方显示常见日期范围的快速选择选项(#10166, #11108)。 - 🏋️ 数据框现在支持
pandas
Styler
对象中定义的字体粗细(#11705, #6461)。 - 🫥 关于对话框默认不会显示在应用菜单中。当前 Streamlit 版本会在设置对话框中显示(#10091)。
- 💅
st.metric
现在为差值使用背景色,类似于st.badge
(#11678)。 - 💻 IDE 现在可以为缓存函数的
.clear()
提供类型提示(#11793, #11821)。感谢 whitphx! - 🔄 修复交换:为了防止多页面应用出现回归问题,
st.context.theme
在首次加载时不会自动重新运行应用。在某些情况下,st.context.theme
可能直到第一次重新运行后才正确(#11870, #11797)。 - 🧹 修复:
st.chat_input
在移动视图下正确显示在屏幕底部(#11896, #11722, #11891)。 - ⏳ 修复:当 WebSocket 重新连接时,应用会完全重新运行以防止丢失片段(#11890, #11660)。
- 🪱 修复:为了减少
No such file or directory
错误,文件监视器现在具有更健壮的异常处理和更清晰的日志记录(#11871, #11841, #11809, #11728)。 - 💩 修复:Vega-Lite 分面图表不再闪烁(#11833)。
- ☠️ 修复:当侧边栏初始状态设置为
"collapsed"
时,侧边栏会正确加载为折叠状态而不会闪烁打开(#11861, #11848)。 - 👽 修复:为了防止应用在稍后时间与当前代码不同步,Streamlit 在所有文件监视器断开连接时清除脚本缓存(#11876, #11739)。感谢 diwu-sf!
- 👻 修复:工具提示中的内联代码与其他 Markdown 文本中的内联代码具有相同的相对大小(#11877)。
- 🦀 修复:
st.multiselect
和st.selectbox
在accept_new_options=True
时显示正确的占位文本(#11623, #11609)。 - 🦋 修复:可以通过切换工具栏图标关闭列可见性菜单(#11857, #11801)。
- 🦎 修复:数据框中的进度条列在进度条和标签之间有正确的内边距(#11685)。
- 🐌 修复:数据框单元格中的警告指示器会根据主题配置调整(#11682)。
- 🕸️ 修复:为了解决数据框中的多个视觉和用户体验问题,更新了
glide-data-grid
(#11677, #8310, #9498, #9471)。 - 🦗 修复:在侧边栏导航部件中,调整了字体间距和粗细以提高视觉清晰度(#11814)。
- 🦂 修复:Altair 图表现在会正确调整宽度以匹配其容器(#11807, #11802)。
- 🦟 修复:运行中图标现在与主题配置匹配(#11461, #11371)。感谢 TreavVasu!
- 🦠 修复:当顶部标题栏包含元素时,背景色正确不透明(#11787, #11785)。
- 🪰 修复:打印时移除了多余的顶部内边距(#11798)。
- 🪳 修复:当
unsafe_allow_html=True
时,Markdown 内联代码正确显示(#11817, #11800)。感谢 bajajku! - 🕷️ 修复:WebSocket ping 间隔不会超过超时间隔(#11693, #11670)。
- 🐞 修复:侧边栏状态在 Community Cloud 上正确初始化,页面内容会根据侧边栏正确滑动和调整大小(#11732, #11702, #11710)。
- 🐝 修复:
st.spinner
中的计时器使用系统时间,防止用户切换到其他浏览器标签时暂停(#11756, #11720)。 - 🐜 修复:带有边框的空容器和空扩展器在添加元素前可见(#11669)。
- 🪲 修复:
st.audio_input
和st.camera_input
具有一致的外观(#11699, #11700)。 - 🐛 修复:为了防止竞态条件,文件监视器正确地对监视路径应用锁(#11692, #11691)。
Streamlit 旧版本
预发布功能
https://docs.streamlit.io/develop/quick-reference/prerelease
在 Streamlit,我们追求快速迭代的同时保持系统稳定。为了在不牺牲稳定性的前提下更快推进,我们为勇敢无畏的用户提供了两种体验前沿功能的方式:
1、实验性功能
2、每日构建版本
实验性功能
稳定性较低的 Streamlit 功能采用统一的命名规范:st.experimental_
。这个特殊前缀会附加在命令名称前,以确保所有人都能清楚了解它们的状态。
以下是不同命名规范所代表的含义:
- st:这里存放着核心功能,如
st.write
和st.dataframe
。如果我们对这些功能进行不兼容的修改,将会逐步推进,并提前数月发布公告和警告。 - experimental:这里存放着所有可能(或不可能)最终进入 Streamlit 核心的新功能。这让你有机会在我们稳定其 API 前的数周或数月,抢先体验我们正在酝酿的重大更新。我们无法确定这些功能是否有未来,但我们希望你能接触到我们尝试的一切,并与我们共同探索。
采用 experimental_
命名规范的功能,代表我们仍在开发或试图理解的功能。如果这些功能取得成功,它们最终会成为 Streamlit 核心的一部分。如果失败,这些功能可能会在未经太多通知的情况下被移除。在实验阶段,功能的 API 和行为可能不稳定,甚至可能发生不兼容的变更。
警告:实验性功能及其 API 可能随时变更或移除。
实验性功能的生命周期
1、功能以experimental_
前缀形式添加。
2、该功能可能会随时间调整,API或行为可能存在破坏性变更。
3、若功能验证成功,我们会将其升级为Streamlit核心功能并移除experimental_
前缀:
- a. 功能API稳定后,会克隆一个不带
experimental_
前缀的版本,此时st
和experimental_
命名空间下会同时存在该功能。用户使用带experimental_
前缀的版本时会收到警告,但功能仍可正常使用。 - b. 后续会移除带
experimental_
前缀的代码实现,但保留函数存根(stub),调用时会显示包含操作指引的错误信息。 - c. 最终在更晚的版本中完全移除
experimental_
前缀版本。
4、若功能验证失败,我们会直接移除该功能(通常不另行通知),并在experimental_
命名空间下保留存根,调用时显示包含指引的错误信息。
夜间版本
除了实验性功能外,我们还提供了另一种体验 Streamlit 最新功能的方式:夜间版本。
每天结束时(夜晚🌛),我们的机器人会对最新的 Streamlit 代码运行自动化测试。如果一切正常,就会将其发布为 streamlit-nightly
包。这意味着夜间版本包含了我们当天代码库中所有最新的功能、错误修复和其他改进。
这与正式版本有何不同?
Streamlit 的正式版本不仅通过了自动化测试,还经过了严格的手动测试,而夜间版本仅包含自动化测试。需要注意的是,夜间版本中引入的新功能通常不够完善。在正式版本中,我们始终会确保所有新功能都完全准备好投入使用。
如何使用夜间版本?
你只需安装 streamlit-nightly
包即可:
pip uninstall streamlit
pip install streamlit-nightly --upgrade
警告:切勿在同一环境中同时安装 streamlit
和 streamlit-nightly
!
为什么应该使用 nightly 版本?
因为你等不及官方正式发布,而且想帮助我们尽早发现错误!
为什么不建议使用 nightly 版本?
虽然我们的自动化测试覆盖率很高,但 nightly 代码中仍存在较大可能出现某些错误。
能否选择安装特定的 nightly 版本?
如果想使用特定版本,可以在 发布历史 中查找版本号。通过 pip
指定所需版本即可:pip install streamlit-nightly==x.yy.zz-123456
。
能否对比不同版本间的变更?
若要查看 nightly 版本的变更内容,可以使用 GitHub 上的对比工具。
知识库
https://docs.streamlit.io/knowledge-base
知识库是一个自助式资源库,包含技巧、分步教程和文章,解答您关于创建和部署Streamlit应用的各种问题。
常见问题 这里汇集了关于使用Streamlit的常见问题解答。
依赖项安装 如果在为Streamlit应用安装依赖项时遇到问题,我们为您提供了解决方案。
部署问题 对将Streamlit应用部署到云端有疑问?本节涵盖与部署相关的问题。
常见问题解答
https://docs.streamlit.io/knowledge-base/using-streamlit
以下是关于使用Streamlit的一些常见问题。如果您觉得缺少了某些重要且大家需要了解的内容,请提交问题或发起拉取请求,我们将很高兴进行审核!
- 完整性检查
- 如何让Streamlit监控我应用中导入的其他模块的变更?
- Streamlit支持哪些浏览器?
- st.file_uploader将上传的文件存储在哪里?何时会被删除?
- 如何获取通过st.file_uploader上传的文件名?
- 如何移除应用标题中的"· Streamlit"?
- 如何在Streamlit中下载文件?
- 如何将Pandas DataFrame下载为CSV文件?
- 如何让
st.pydeck_chart
使用自定义Mapbox样式? - 如何乱序插入元素?
- 如何升级到最新版Streamlit?
- 使用会话状态时,小部件为何会对每个输入进行更新
- 如何创建锚点链接?
- 如何启用摄像头访问权限?
- 为什么Streamlit限制嵌套的
st.columns
? - 什么是可序列化的会话状态?
安装依赖项
https://docs.streamlit.io/knowledge-base/dependencies
- ModuleNotFoundError: 找不到模块
- ImportError: libGL.so.1: 无法打开共享对象文件: 没有该文件或目录
- ERROR: 找不到匹配的发行版
- 如何安装不在PyPI/Conda但在GitHub上可用的包
上一页: 常见问题
下一页: 如何安装不在PyPI或Conda但在GitHub上可用的包
部署相关问题和错误
https://docs.streamlit.io/knowledge-base/deploy
- 如何将Streamlit部署到域名使其看起来运行在常规端口(如80端口)?
- 如何在不同子域名上部署多个Streamlit应用?
- 在已部署的Streamlit应用中调用Python子进程
- Streamlit是否支持WSGI协议?(即能否用gunicorn部署Streamlit?)
- 糟糕。此应用已超出资源限制。
- 远程运行时应用无法加载
- 不使用SSO的身份验证
- 如何在Streamlit Community Cloud上增加
st.file_uploader
的上传限制? - 尝试登录后显示"呃,这不应该发生"的消息
- 尝试登录Streamlit Community Cloud失败并返回403错误
- 如何为Streamlit Community Cloud提交支持案例
上一页:安装依赖项
下一页:如何在不同子域名上部署多个Streamlit应用?
2025-07-19(六)