首页 > 解决方案 > 使用 plot.ly Dash 等待结果时显示加载符号

问题描述

在我的基于Dash的应用程序中,一个按钮会触发一个长时间运行的计算。在结果尚未出现时显示加载动画并让按钮处于非活动状态以便在计算完成之前不会再次单击它不是很好吗?

我正在使用Bulma进行 UI 设计,并希望button is-loading为此目的使用 CSS 类。

在此处输入图像描述

我的第一个想法是有两个回调:一个由按钮单击触发以将按钮设置为is-loading,另一个由输出更改触发以将其设置为正常。

@app.callback(
    Output('enter-button', 'className'),
    [
        Input('graph', 'figure')
    ],
)
def set_trend_enter_button_loading(figure_changed):
    return "button is-large is-primary is-outlined"


@app.callback(
    Output('enter-button', 'className'),
    [
        Input('enter-button', 'n_clicks')
    ],
)
def set_trend_enter_button_loading(n_clicks):
    return "button is-large is-primary is-outlined is-loading"

显然它不是这样工作的:

dash.exceptions.CantHaveMultipleOutputs:
You have already assigned a callback to the output
with ID "enter-button" and property "className". An output can only have
a single callback function. Try combining your inputs and
callback functions together into one function.

任何想法如何使这项工作?

标签: pythoncssuser-interfacedashboardplotly-dash

解决方案


上周我遇到了同样的问题,甚至尝试使用 Javascript 实现禁用按钮的行为,但最终放弃了。我在plotly 论坛上看到过这个讨论,显然需要这种类型的功能,但我认为在当前版本中不容易实现。

不过,有一件事情可能的,并且被 Dash 开发人员作为临时解决方案提到,那就是添加一个全局加载屏幕。简而言之,您需要将以下 CSS 添加到样式表中:

@keyframes fadein {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 0.5;
    }
}

._dash-loading-callback {
  font-family: sans-serif;
  padding-top: 50px;
  color: rgb(90, 90, 90);

  /* The banner */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  cursor: progress;

  opacity: 0;
  background-color: rgb(250, 250, 250);
  /* Delay animation by 1s to prevent flashing 
     and smoothly transition the animation over 0.5s 
   */
  -moz-animation: fadein 0.5s ease-in 1s forwards; /* Firefox */
  -webkit-animation: fadein 0.5s ease-in 1s forwards; /* Safari and Chrome */
  -o-animation: fadein 0.5s ease-in 1s forwards; /* Opera */
    animation: fadein 0.5s ease-in 1s forwards;
}

一些澄清:

  • 选择器_dash-loading-callback选择一个 div,它在每次回调时添加到 body 元素的末尾,并在完成时删除。
  • 您可以通过为_dash-loading-callback.
  • 上述 CSS 中定义的动画旨在防止加载屏幕在短回调时闪烁。它设置为在一秒钟后淡入,因此它只会在长时间加载操作时出现。您当然可以使用这些设置。

推荐阅读