You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Streamlit应用添加固定静态背景图片

在Streamlit中添加固定背景图片的方法

Streamlit没有原生支持设置固定背景图的API,但可以通过注入自定义CSS实现需求。以下是具体步骤:

1. 准备背景图片

将你要使用的静态图片放在Streamlit脚本的同一目录下(比如命名为background.jpg),或者准备好图片的在线URL。

2. 注入自定义CSS

使用st.markdown()方法注入包含背景样式的CSS代码,核心是通过background-attachment: fixed实现背景固定效果:

import streamlit as st

# 注入背景样式
st.markdown(
    """
    <style>
    .stApp {
        background-image: url("background.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center;
    }
    </style>
    """,
    unsafe_allow_html=True
)

# 示例应用内容
st.title("带固定背景的Streamlit应用")
st.write("向下滚动页面,背景图片会保持固定不动")

# 添加足够多的内容让页面可滚动
for _ in range(50):
    st.write("测试滚动内容行")

关键CSS属性说明

  • background-image:指定背景图片路径,本地图片直接写文件名(需和脚本同目录),在线图片填写完整URL。
  • background-attachment: fixed:强制背景图片固定在视口,不随页面滚动移动。
  • background-size: cover:让图片按比例覆盖整个页面,超出部分会被裁剪。
  • background-position: center:将图片居中显示在页面。

优化内容可读性(可选)

如果背景图片导致文字难以阅读,可以给内容区域添加半透明背景:

st.markdown(
    """
    <style>
    .stApp {
        background-image: url("background.jpg");
        background-attachment: fixed;
        background-size: cover;
        background-position: center;
    }
    .stMarkdown, .stTitle {
        background-color: rgba(255, 255, 255, 0.9);
        padding: 1rem;
        border-radius: 8px;
    }
    </style>
    """,
    unsafe_allow_html=True
)

这样页面中的标题和文本区域会有半透明白色背景,提升文字可读性。

内容的提问来源于stack exchange,提问作者K80

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:20:35