如何使用os模块实现Streamlit中文件列表默认折叠显示
解决Streamlit文件列表默认折叠的问题
要实现默认折叠的文件列表,直接用st.write显示列表无法达成需求,你可以使用Streamlit内置的st.expander组件,它支持默认折叠状态,点击后再展开内容。
修改后的代码
import os import streamlit as st # 创建默认折叠的expander,标题为文件夹名称 with st.expander("📁 1 docx-raw", expanded=False): filelist = [] for root, dirs, files in os.walk("/home/lungsang/Desktop/levelpack-UI/content/A0/1 docx-raw"): for file in files: filename = os.path.join(root, file) filelist.append(filename) st.write(filelist)
关键说明
st.expander的参数expanded=False是核心,设置后组件默认处于折叠状态- 将文件列表的生成和显示逻辑放在
with代码块内,内容就会被包裹在可折叠容器中 - 点击expander标题即可展开查看完整文件列表,收起后页面会更整洁
内容的提问来源于stack exchange,提问作者lungsang
相关产品推荐
相关产品推荐

