在Streamlit应用中批量展示同一文件夹下的本地GIF图像,核心是通过Python遍历文件夹获取所有GIF文件路径,再结合Streamlit的图像展示组件完成渲染,整个流程不需要手动逐个配置路径,适配文件数量动态变化的场景。

实现前的环境准备
首先需要确保已经安装Streamlit库,如果未安装可以通过pip命令完成安装:
pip install streamlit
同时需要准备一个存放GIF图像的文件夹,假设文件夹路径为./gif_files,该文件夹下存放所有需要展示的本地GIF文件。
核心实现步骤
1. 遍历文件夹筛选GIF文件
使用Python的os模块遍历目标文件夹,筛选出所有后缀为.gif的文件,同时可以过滤掉非文件类型的目录项,避免后续加载出错。
import os
# 目标GIF文件夹路径,可根据实际情况修改
gif_dir = "./gif_files"
# 存储所有GIF文件路径的列表
gif_paths = []
# 遍历文件夹下的所有条目
for filename in os.listdir(gif_dir):
# 拼接完整文件路径
full_path = os.path.join(gif_dir, filename)
# 判断是否为文件且后缀为gif(不区分大小写)
if os.path.isfile(full_path) and filename.lower().endswith(".gif"):
gif_paths.append(full_path)
2. 在Streamlit中展示GIF图像
Streamlit提供了st.image函数可以直接展示本地图像文件,将获取到的GIF路径列表传入即可批量渲染,还可以添加标题、调整展示宽度等参数优化展示效果。
import streamlit as st
# 设置页面标题
st.title("本地GIF图像批量展示")
# 判断是否存在GIF文件
if len(gif_paths) == 0:
st.warning("目标文件夹下未找到GIF图像文件")
else:
# 遍历所有GIF路径依次展示
for idx, gif_path in enumerate(gif_paths):
# 展示GIF文件名作为标题
st.subheader(f"GIF图像 {idx + 1}: {os.path.basename(gif_path)}")
# 展示GIF图像,设置宽度为400像素
st.image(gif_path, width=400)
完整示例代码
将上面的两部分代码整合,同时添加必要的异常捕获逻辑,避免文件夹不存在等错误导致程序崩溃,完整代码如下:
import os
import streamlit as st
def show_local_gifs(gif_dir):
# 检查文件夹是否存在
if not os.path.exists(gif_dir):
st.error(f"指定的文件夹 {gif_dir} 不存在")
return
if not os.path.isdir(gif_dir):
st.error(f"{gif_dir} 不是一个有效的文件夹")
return
gif_paths = []
# 遍历文件夹筛选GIF文件
for filename in os.listdir(gif_dir):
full_path = os.path.join(gif_dir, filename)
if os.path.isfile(full_path) and filename.lower().endswith(".gif"):
gif_paths.append(full_path)
# 展示GIF图像
st.title("本地GIF图像批量展示")
if len(gif_paths) == 0:
st.warning("目标文件夹下未找到GIF图像文件")
else:
for idx, gif_path in enumerate(gif_paths):
st.subheader(f"GIF图像 {idx + 1}: {os.path.basename(gif_path)}")
st.image(gif_path, width=400)
if __name__ == "__main__":
# 可修改为目标GIF文件夹的实际路径
target_dir = "./gif_files"
show_local_gifs(target_dir)
注意事项
- 如果GIF文件较大,加载时可能会有短暂延迟,可以通过调整
st.image的width参数缩小展示尺寸,提升加载速度。 - 若需要展示其他格式的图像,只需要修改筛选条件中的后缀判断逻辑,比如添加
.png、.jpg等后缀即可。 - 运行程序时需要在命令行执行
streamlit run 文件名.py,不能直接通过Python解释器运行。