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

如何为Dash的dcc.Loading内置加载器添加文字说明

问题描述

我希望使用dcc.Loading中的内置加载器,但要在加载器激活时在其下方添加文字说明。现有代码如下:

import time
import plotly.express as px
import dash_mantine_components as dmc
import dash
from dash import dcc, callback, Output, Input

dash.register_page(module=__name__)

layout = dmc.MantineProvider(
    children=[
        dmc.Select(
            id="dropdown",
            data=["bar", "scatter", "none"],
            value="bar",
        ),
        dcc.Loading(
            type="graph",
            children=dmc.Box(id="my_figure")
        )
    ]
)


@callback(
    Output("my_figure", "children"),
    Input("dropdown", "value")
)
def show_fig(value):
    if value == "bar":
        time.sleep(5)
        return dcc.Graph(figure=px.bar())
    elif value == "scatter":
        time.sleep(5)
        return dcc.Graph(figure=px.scatter())
    else:
        return []

当前代码仅显示graph类型的加载器,无文字内容。请问是否可以不使用custom_spinner参数实现添加文字的需求?还是必须重写内置加载器并将其传入custom_spinner参数?

解决方案

不需要必须使用custom_spinner参数,可以通过以下方式实现需求:

方法:利用CSS类控制文字显示

dcc.Loading在激活状态时,会给其父级元素自动添加dash-loading类,我们可以借助这个类来控制提示文字的显示与隐藏,无需修改内置加载器:

import time
import plotly.express as px
import dash_mantine_components as dmc
import dash
from dash import dcc, callback, Output, Input, html

dash.register_page(module=__name__)

layout = dmc.MantineProvider(
    children=[
        dmc.Select(
            id="dropdown",
            data=["bar", "scatter", "none"],
            value="bar",
        ),
        # 外层容器,包裹加载器和提示文字
        html.Div(
            children=[
                dcc.Loading(
                    type="graph",
                    children=dmc.Box(id="my_figure")
                ),
                # 默认隐藏的加载提示文字
                html.Div(
                    "数据加载中,请稍候...",
                    id="loading-text",
                    style={"display": "none", "textAlign": "center", "marginTop": "10px", "color": "#666"}
                )
            ]
        ),
        # 注入CSS规则,加载状态下显示文字
        html.Style("""
            .dash-loading #loading-text {
                display: block !important;
            }
        """)
    ]
)


@callback(
    Output("my_figure", "children"),
    Input("dropdown", "value")
)
def show_fig(value):
    if value == "bar":
        time.sleep(5)
        return dcc.Graph(figure=px.bar())
    elif value == "scatter":
        time.sleep(5)
        return dcc.Graph(figure=px.scatter())
    else:
        return []

如果需要对加载器和文字的布局做更个性化的定制,也可以选择使用custom_spinner参数,但这并非实现需求的必要方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:37:23