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

如何在Spinner运行时保持其后方图像可见?

让Dash Spinner运行期间后方图像保持可见的解决方案

问题出在你当前的代码把图像放在了dbc.Spinner的子组件里——默认情况下,当Spinner处于激活状态时,它会隐藏内部的子元素。要让图像保持可见,我们需要调整布局,让Spinner作为叠加层覆盖在图像上方,而不是把图像包裹在Spinner内部。

下面是修改后的完整代码:

from dash import Dash, html, callback, Output, Input
from time import sleep
import dash_bootstrap_components as dbc

app = Dash(__name__, external_stylesheets=[dbc.themes.CYBORG])
app.layout = html.Div(
    style={'position': 'relative', 'min-height': '10rem', 'min-width': '10rem', 'margin-left':'10rem'},
    children=[
        # 图像作为底层元素,始终显示
        html.Img(src='https://dash.plotly.com/assets/images/plotly_logo_dark.png', style={'width': '100%'}),
        # Spinner作为叠加层,绝对定位覆盖在图像上
        dbc.Spinner(
            html.Div(id='spinner'),
            spinner_style={
                'position': 'absolute',
                'top': 0,
                'left': 0,
                'right': 0,
                'bottom': 0,
                'background-color': 'transparent',  # 背景透明,让下方图像透出来
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center'
            },
            color="light"  # 调整Spinner颜色,和深色图像形成对比更醒目
        ),
        html.Div(dbc.Button('Button', id='button', size="lg", className="me-1"))
    ]
)

@callback(
    Output('spinner', 'children'),
    Input('button', 'n_clicks'),
    prevent_initial_call=True,
)
def process(value: str):
    sleep(1)
    return ''

if __name__ == '__main__':
    app.run(debug=True)

关键改动说明:

  • 用一个position: relative的容器包裹图像和Spinner,让Spinner可以通过绝对定位相对于容器居中覆盖。
  • 给Spinner设置background-color: transparent,避免遮挡下方图像。
  • 将图像移出Spinner的子组件范围,确保它不受Spinner加载状态的隐藏规则影响。
  • 调整Spinner的布局样式,让它在图像上方居中显示,同时保留原有的尺寸位置。

如果想要Spinner的样式更贴合需求,还可以修改spinner_type参数(比如设置为"border"),搭配不同的color值来优化视觉效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 09:54:06