Streamlit 可视化

API 整理

文件上传

st.file_uploader

区别于文件接口,该 API 返回的是字节字符串,即 b'???' 形式。这导致无法直接处理。

解决方案是在 Parser 类中加一层转换,同时进行乱码处理

1
file = io.TextIOWrapper(raw_file, encoding='utf-8', errors='ignore')

此时就可以使用 file.readlines() 等常用 API 进行处理了。

按钮

st.button(name)

点击事件可通过 if 触发

1
2
if st.button():
...

复选框

st.checkbox

下拉框

st.selectbox

下拉框 (多选)

st.multiselect

e.g. 将表格首列条目作为备选列表

1
2
df = pandas.read_excel()
channels = st.multiselect(MSG, df[df.columns[0]].tolist(), ["first_elem"])

布局

Tabs

以标签分隔的多个多元素容器,使用 with 编辑。

1
2
3
4
5
tab1. tab2 = st.tabs(['tag1', 'tag2'])
with tab1:
st.do_something()
with tab2:
...

with 块内仍使用 st 描述即可。

列布局

可指定分隔为数个列,并指定列宽比例。

1
2
3
cols = st.columns([1, 2]) # 1:2 双列
cols[0].dataframe(data)
...

e.g. 多行多列

1
2
3
4
5
cols1 = st.columns([1, 1])
cols2 = st.columns([1, 1])
cols = cols1 + cols2
cols[0].markdown()
...

Container

st.container

可作为多种容器的子容器,如根容器 st 和列容器 col,笔者用它与列容器联合,同时进行宽高控制

1
2
col1, col2 = st.columns([1, 2]) # 宽度控制
col1.container(height=height, border=False) # 高度控制

Session

st.session_state

满昏!简单且用户友好的 Session 机制。当成字典用即可。

数据分析

展示列表

st.dataframe

直接 write 其实也行

功能

Streamlit 功能 API.

重运行

st.rerun

用于某些操作后刷新页面。

装饰器

e.g. Cache 装饰器,@st.cache_data

引用

  1. [重要] Streamlit 完整教程
  2. Streamlit Session_State
  3. Streamlit 布局篇