API reference
Streamlit 使您可以轻松地可视化、转换和共享数据。API 参考按活动类型组织,例如显示数据或优化性能。每个部分包括与该活动类型相关的方法,包括示例。
浏览我们的API,点击了解更多关于我们可用命令的信息!🎈
Display almost anything
Write and magic
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
Text elements

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

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

标题
在标题格式中显示文本。
st.header("This is a header")

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

标题
以小字体显示文本。
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()
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Data elements

数据框
将数据框显示为交互式表格。
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)
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Chart elements

简单面积图
显示一个区域图。
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)
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Input widgets
按钮
显示一个按钮小部件。
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")
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Media elements

图像
显示一张图片或图片列表。
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")
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Layouts and containers

列
插入布局为并排列的容器。
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 show first")
c.write("This will show second")

模态对话框
插入一个可以独立于脚本其余部分重新运行的模态对话框。
@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")
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Chat elements
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)
Status elements

进度条
显示一个进度条。
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()

提示信息
在右下角短暂显示一条提示消息。
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)
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
App logic and configuration
Navigation and pages

导航
在多页面应用程序中配置可用的页面。
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")
Execution flow

模态对话框
插入一个可以独立于脚本其余部分重新运行的模态对话框。
@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()
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Caching and state
缓存数据
函数装饰器,用于缓存返回数据的函数(例如数据框转换、数据库查询、机器学习推理)。
@st.cache_data
def long_function(param1, param2):
# Perform expensive computation here or
# fetch data from the web here
return data
缓存资源
函数装饰器,用于缓存返回全局资源(例如数据库连接、ML模型)的函数。
@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()
Connections and databases
设置您的连接
创建连接
连接到数据源或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')
SQL连接
使用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"]
密钥文件
将您的秘密保存在每个项目或每个配置文件的TOML文件中。
OpenAI_key = "<YOUR_SECRET_KEY>"
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
Custom Components
声明一个组件
创建并注册一个自定义组件。
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"
)
Utilities and user info
上下文
st.context
提供了一个只读接口来访问cookies和headers。
st.context.cookies
st.context.headers
获取帮助
显示对象的文档字符串,格式良好。
st.help(st.write)
st.help(pd.DataFrame)
渲染HTML
将HTML字符串渲染到您的应用程序中。
st.html("<p>Foo bar.</p>")
用户信息
st.experimental_user
返回有关Streamlit Community Cloud上私有应用程序的登录用户的信息。
if st.experimental_user.email == "foo@corp.com":
st.write("Welcome back, ", st.experimental_user.email)
else:
st.write("You are not authorized to view this page.")
Configuration
配置文件
配置应用程序的默认设置。
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:",
)
Developer tools
App testing
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()
第三方组件
这些是由我们可爱的社区创建的精选组件。更多示例和灵感,请查看我们的 Components Gallery 和 Streamlit Extras!
还有问题吗?
我们的 论坛 充满了有用的信息和Streamlit专家。