API 参考
Streamlit 使您可以轻松地可视化、修改和共享数据。API 参考按活动类型组织,例如显示数据或优化性能。每个部分都包含与该活动类型相关的方法,并提供示例。
浏览下面的 API 并点击以了解更多可用命令!🎈
显示几乎所有内容
写入与魔术方法
st.write
将参数写入应用。
st.write("Hello **world**!") st.write(my_data_frame) st.write(my_mpl_figure)
st.write_stream
以打字机效果将生成器或流写入应用。
st.write_stream(my_generator) st.write_stream(my_llm_stream)
魔术方法
任何时候 Streamlit 在独立行上看到变量或字面值时,它都会使用 st.write
自动将其写入您的应用
"Hello **world**!" my_data_frame my_mpl_figure
文本元素

Markdown
显示格式化为 Markdown 的字符串。
st.markdown("Hello **world**!")

标题
以标题格式显示文本。
st.title("The app title")

一级标题
以一级标题格式显示文本。
st.header("This is a header")

二级标题
以二级标题格式显示文本。
st.subheader("This is a subheader")

徽章
显示小型彩色徽章。
st.badge("New")

说明文字
以小字体显示文本。
st.caption("This is written small caption text")

代码块
显示带有可选语法高亮的代码块。
st.code("a = 1234")

回显
在应用中显示代码,然后执行。适用于教程。
with st.echo(): st.write('This code will be printed')

LaTeX
显示格式化为 LaTeX 的数学表达式。
st.latex("\int a x^2 \,dx")

预格式化文本
写入固定宽度和预格式化文本。
st.text("Hello world")

分隔线
显示水平分隔线。
st.divider()
获取帮助
漂亮地格式化并显示对象的文档字符串。
st.help(st.write) st.help(pd.DataFrame)
渲染 HTML
将 HTML 字符串渲染到您的应用。
st.html("<p>Foo bar.</p>")
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
数据元素

数据框
将数据框显示为交互式表格。
st.dataframe(my_data_frame)

数据编辑器
显示数据编辑器组件。
edited = st.data_editor(df, num_rows="dynamic")

列配置
配置数据框和数据编辑器的显示和编辑行为。
st.column_config.NumberColumn("Price (in USD)", min_value=0, format="$%d")

静态表格
显示静态表格。
st.table(my_data_frame)

指标
以大号粗体字体显示指标,并可选择显示指标变化指示器。
st.metric("My metric", 42, 2)

字典和 JSON
将对象或字符串显示为漂亮格式化的 JSON 字符串。
st.json(my_dict)
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
图表元素

简单面积图
显示面积图。
st.area_chart(my_data_frame)

简单条形图
显示条形图。
st.bar_chart(my_data_frame)

简单折线图
显示折线图。
st.line_chart(my_data_frame)
简单散点图
显示散点图。
st.scatter_chart(my_data_frame)

地图上的散点图
在地图上显示带有点的地图。
st.map(my_data_frame)

Matplotlib
显示 matplotlib.pyplot 图。
st.pyplot(my_mpl_figure)

Altair
使用 Altair 库显示图表。
st.altair_chart(my_altair_chart)

Vega-Lite
使用 Vega-Lite 库显示图表。
st.vega_lite_chart(my_vega_lite_chart)

Plotly
显示交互式 Plotly 图表。
st.plotly_chart(my_plotly_chart)

Bokeh
显示交互式 Bokeh 图表。
st.bokeh_chart(my_bokeh_chart)

PyDeck
使用 PyDeck 库显示图表。
st.pydeck_chart(my_pydeck_chart)

GraphViz
使用 dagre-d3 库显示图。
st.graphviz_chart(my_graphviz_spec)
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
输入组件
按钮
显示按钮组件。
clicked = st.button("Click me")
下载按钮
显示下载按钮组件。
st.download_button("Download file", file)
表单按钮
显示表单提交按钮。与 st.form
配合使用。
st.form_submit_button("Sign up")
链接按钮
显示链接按钮。
st.link_button("Go to gallery", url)

页面链接
在多页面应用中显示指向另一个页面的链接。
st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile")

复选框
显示复选框组件。
selected = st.checkbox("I agree")

颜色选择器
显示颜色选择器组件。
color = st.color_picker("Pick a color")

反馈
显示评分或情感按钮组。
st.feedback("stars")

多选框
显示多选组件。多选组件初始为空。
choices = st.multiselect("Buy", ["milk", "apples", "potatoes"])

药丸按钮
显示药丸按钮选择组件。
st.pills("Tags", ["Sports", "AI", "Politics"])

单选框
显示单选按钮组件。
choice = st.radio("Pick one", ["cats", "dogs"])

分段控件
显示分段按钮选择组件。
st.segmented_control("Filter", ["Open", "Closed", "All"])

选择框
显示选择组件。
choice = st.selectbox("Pick one", ["cats", "dogs"])

选择滑块
显示用于从列表中选择项目的滑块组件。
size = st.select_slider("Pick a size", ["S", "M", "L"])

开关
显示开关组件。
activated = st.toggle("Activate")

数字输入
显示数字输入组件。
choice = st.number_input("Pick a number", 0, 10)

滑块
显示滑块组件。
number = st.slider("Pick a number", 0, 100)

日期输入
显示日期输入组件。
date = st.date_input("Your birthday")

时间输入
显示时间输入组件。
time = st.time_input("Meeting time")

聊天输入框
显示聊天输入框组件。
prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}")

文本区域
显示多行文本输入组件。
text = st.text_area("Text to translate")

文本输入
显示单行文本输入组件。
name = st.text_input("First name")

音频输入
显示允许用户使用麦克风录音的组件。
speech = st.audio_input("Record a voice message")

数据编辑器
显示数据编辑器组件。
edited = st.data_editor(df, num_rows="dynamic")

文件上传器
显示文件上传器组件。
data = st.file_uploader("Upload a CSV")

摄像头输入
显示允许用户直接从摄像头上传图像的组件。
image = st.camera_input("Take a picture")
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
媒体元素

图像
显示图像或图像列表。
st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg")

徽标
在应用的左上角及其侧边栏中显示徽标。
st.logo("logo.jpg")

音频
显示音频播放器。
st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3")

视频
显示视频播放器。
st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4")
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
布局和容器

列
插入并排布局的容器。
col1, col2 = st.columns(2) col1.write("this is column 1") col2.write("this is column 2")

容器
插入多元素容器。
c = st.container() st.write("This will show last") c.write("This will be replaced") c.write("This will show first")

模态对话框
插入一个可以独立于脚本其余部分重新运行的模态对话框。
@st.dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email")

空容器
插入单元素容器。
c = st.empty() st.write("This will show last") c.write("This will be replaced") c.write("This will show first")

可展开容器
插入可展开/折叠的多元素容器。
with st.expander("Open to see more"): st.write("This is more content")
弹出框
插入可打开/关闭的多元素弹出框容器。
with st.popover("Settings"): st.checkbox("Show completed")

侧边栏
在侧边栏中显示项目。
st.sidebar.write("This lives in the sidebar") st.sidebar.button("Click me!")

选项卡
插入按选项卡分隔的容器。
tab1, tab2 = st.tabs(["Tab 1", "Tab2"]) tab1.write("this is tab 1") tab2.write("this is tab 2")
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
聊天元素
Streamlit 提供了一些命令来帮助您构建对话式应用。这些聊天元素旨在协同使用,但您也可以单独使用它们。
st.chat_message
允许您在应用中插入聊天消息容器,以便显示用户或应用的消息。聊天容器可以包含其他 Streamlit 元素,包括图表、表格、文本等。st.chat_input
允许您显示聊天输入组件,以便用户可以输入消息。

聊天输入框
显示聊天输入框组件。
prompt = st.chat_input("Say something") if prompt: st.write(f"The user has sent: {prompt}")

聊天消息
插入聊天消息容器。
import numpy as np with st.chat_message("user"): st.write("Hello 👋") st.line_chart(np.random.randn(30, 3))

状态容器
在容器中显示长时间运行任务的输出。
with st.status('Running'): do_something_slow()
st.write_stream
以打字机效果将生成器或流写入应用。
st.write_stream(my_generator) st.write_stream(my_llm_stream)
状态元素

进度条
显示进度条。
for i in range(101): st.progress(i) do_something_slow()

微调器
在执行代码块时临时显示消息。
with st.spinner("Please wait..."): do_something_slow()

状态容器
在容器中显示长时间运行任务的输出。
with st.status('Running'): do_something_slow()

Toast 消息
在右下角短暂显示 Toast 消息。
st.toast('Butter!', icon='🧈')

气球
显示庆祝气球!
do_something() # Celebrate when all done! st.balloons()

雪花
显示庆祝雪花!
do_something() # Celebrate when all done! st.snow()

成功框
显示成功消息。
st.success("Match found!")

信息框
显示信息消息。
st.info("Dataset is updated every day at midnight.")

警告框
显示警告消息。
st.warning("Unable to fetch image. Skipping...")

错误框
显示错误消息。
st.error("We encountered an error")

异常输出
显示异常。
e = RuntimeError("This is an exception of type RuntimeError") st.exception(e)
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
应用逻辑和配置
认证和用户信息
用户登录
st.login()
启动与身份提供者的认证流程。
st.login()
用户注销
st.logout()
移除用户的身份信息。
st.logout()
用户信息
st.user
返回已登录用户的信息。
if st.user.is_logged_in: st.write(f"Welcome back, {st.user.name}!")
导航和页面

导航
配置多页面应用中的可用页面。
st.navigation({ "Your account" : [log_out, settings], "Reports" : [overview, usage], "Tools" : [search] })

页面
在多页面应用中定义页面。
home = st.Page( "home.py", title="Home", icon=":material/home:" )

页面链接
在多页面应用中显示指向另一个页面的链接。
st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="My profile")
切换页面
通过编程导航到指定的页面。
st.switch_page("pages/my_page.py")
执行流程

模态对话框
插入一个可以独立于脚本其余部分重新运行的模态对话框。
@st.dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email")
表单
创建包含元素和“提交”按钮的表单。
with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up")
片段
定义一个片段,使其独立于脚本其余部分重新运行。
@st.fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df)
重新运行脚本
立即重新运行脚本。
st.rerun()
停止执行
立即停止执行。
st.stop()
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
缓存和状态
缓存数据
用于缓存返回数据(例如数据框转换、数据库查询、机器学习推理)的函数的装饰器。
@st.cache_data def long_function(param1, param2): # Perform expensive computation here or # fetch data from the web here return data
缓存资源
用于缓存返回全局资源(例如数据库连接、机器学习模型)的函数的装饰器。
@st.cache_resource def init_model(): # Return a global resource here return pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" )
会话状态
会话状态是一种在每次用户会话的重新运行之间共享变量的方式。
st.session_state['key'] = value
查询参数
获取、设置或清除浏览器 URL 地址栏中显示的查询参数。
st.query_params[key] = value st.query_params.clear()
上下文
st.context
提供一个只读接口来访问 cookie、header、区域设置和其他浏览器会话信息。
st.context.cookies st.context.headers
连接和数据库
设置连接
创建连接
连接到数据源或 API
conn = st.connection('pets_db', type='sql') pet_owners = conn.query('select * from pet_owners') st.dataframe(pet_owners)
内置连接
SnowflakeConnection
连接到 Snowflake。
conn = st.connection('snowflake')
SQLConnection
使用 SQLAlchemy 连接到 SQL 数据库。
conn = st.connection('sql')
构建自定义连接
连接基类
使用 BaseConnection
构建自定义连接。
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)
密钥管理
Secrets 单例
从本地 TOML 文件访问密钥。
key = st.secrets["OpenAI_key"]
Secrets 文件
将您的密钥保存在每个项目或每个配置文件的 TOML 文件中。
your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
自定义组件
声明组件
创建并注册自定义组件。
from st.components.v1 import declare_component declare_component( "custom_slider", "/frontend", )
HTML
在 iframe 中显示 HTML 字符串。
from st.components.v1 import html html( "<p>Foo bar.</p>" )
iframe
在 iframe 中加载远程 URL。
from st.components.v1 import iframe iframe( "docs.streamlit.io" )
配置
配置文件
配置应用的默认设置。
your-project/ ├── .streamlit/ │ └── config.toml └── your_app.py
获取配置选项
检索单个配置选项。
st.get_option("theme.primaryColor")
设置配置选项
设置单个配置选项。(此功能非常有限。)
st.set_option("deprecation.showPyplotGlobalUse", False)
设置页面标题、网站图标等
配置页面的默认设置。
st.set_page_config( page_title="My app", page_icon=":shark:", )
开发者工具
应用测试
st.testing.v1.AppTest
st.testing.v1.AppTest
模拟正在运行的 Streamlit 应用进行测试。
from streamlit.testing.v1 import AppTest at = AppTest.from_file("streamlit_app.py") at.secrets["WORD"] = "Foobar" at.run() assert not at.exception at.text_input("word").input("Bazbat").run() assert at.warning[0].value == "Try again."
AppTest.from_file
st.testing.v1.AppTest.from_file
从文件初始化模拟应用。
from streamlit.testing.v1 import AppTest at = AppTest.from_file("streamlit_app.py") at.run()
AppTest.from_string
st.testing.v1.AppTest.from_string
从字符串初始化模拟应用。
from streamlit.testing.v1 import AppTest at = AppTest.from_string(app_script_as_string) at.run()
AppTest.from_function
st.testing.v1.AppTest.from_function
从函数初始化模拟应用。
from streamlit.testing.v1 import AppTest at = AppTest.from_function(app_script_as_callable) at.run()
块
容器元素的表示,包括:
st.chat_message
st.columns
st.sidebar
st.tabs
- 应用的主体。
# at.sidebar returns a Block at.sidebar.button[0].click().run() assert not at.exception
元素
所有元素表示的基类,包括:
st.title
st.header
st.markdown
st.dataframe
# at.title returns a sequence of Title # Title inherits from Element assert at.title[0].value == "My awesome app"
按钮
st.button
和 st.form_submit_button
的表示。
at.button[0].click().run()
聊天输入框
st.chat_input
的表示。
at.chat_input[0].set_value("What is Streamlit?").run()
复选框
st.checkbox
的表示。
at.checkbox[0].check().run()
颜色选择器
st.color_picker
的表示。
at.color_picker[0].pick("#FF4B4B").run()
日期输入
st.date_input
的表示。
release_date = datetime.date(2023, 10, 26) at.date_input[0].set_value(release_date).run()
多选框
st.multiselect
的表示。
at.multiselect[0].select("New York").run()
数字输入
st.number_input
的表示。
at.number_input[0].increment().run()
单选框
st.radio
的表示。
at.radio[0].set_value("New York").run()
选择滑块
st.select_slider
的表示。
at.select_slider[0].set_range("A","C").run()
选择框
st.selectbox
的表示。
at.selectbox[0].select("New York").run()
滑块
st.slider
的表示。
at.slider[0].set_range(2,5).run()
文本区域
st.text_area
的表示。
at.text_area[0].input("Streamlit is awesome!").run()
文本输入
st.text_input
的表示。
at.text_input[0].input("Streamlit").run()
时间输入
st.time_input
的表示。
at.time_input[0].increment().run()
开关
st.toggle
的表示。
at.toggle[0].set_value("True").run()
第三方组件
这些是由我们可爱的社区创建的精选组件。如需更多示例和灵感,请查看我们的 组件库 和 Streamlit Extras!
还有问题吗?
我们的 论坛 充满了有用的信息和 Streamlit 专家。