Streamlit

2025-09-18

Streamlit 是一款开源的 [[Python]] 框架。

安装

通过 [[pip]] 安装:

Terminal window
pip install streamlit

运行官方 DEMO Hello 应用验证:

Terminal window
streamlit hello

如果是自己开发的,则使用 run 运行:

Terminal window
streamlit run demo

API

布局

st.columns

并排布局。

import streamlit as st
col1, col2 = st.columns(2)
with col1:
st.header("A cat")
st.image("https://static.streamlit.io/examples/cat.jpg")
with col2:
st.header("A dog")
st.image("https://static.streamlit.io/examples/dog.jpg")

如果 coolumns 中的值是一个元组,则按照指定比例划分:

Terminal window
# 3 和 7 比例
col1, col2 = st.columns((3, 7))

输入

st.selectbox

选择(单选)。

import streamlit as st
option = st.selectbox(
"How would you like to be contacted?",
("Email", "Home phone", "Mobile phone"),
)
st.write("You selected:", option)

参数:

  • index: 初始值的索引;默认 0,为 None 时初始化为空
  • accept_new_options: 是否支持自定义添加,默认 False

st.multiselect

选择 (多选)。

import streamlit as st
options = st.multiselect(
"你最喜欢的颜色?",
["蓝色", "红色", "黄色"]
)
st.write("你最喜欢的颜色是:", options)
  • default: 默认选中的选项,支持单个和多个,默认 None
  • placeholder: 占位符,默认是 None

st.text_area

多行文本。

txt = st.text_area(
"Hello, World."
)
  • height: 高度,默认是 None,可选 (content, stretch)

文本

st.title

以标题格式显示文本。

import streamlit as st
st.title("This is a title")