如何在没有输入的情况下使用破折号回调

How to use dash callback without an Input

我正在尝试在没有 Input 的情况下调用 plotly-dash 回调,但该方法不会触发。

这是我尝试使用破折号构建的仪表板。过去,当我将回调与输入和输出一起使用时,一切正常,但当我尝试仅使用输出时,结果未显示在仪表板上。

html.Div(
    [

        html.P(
            "Tweet Count",
            className="twelve columns indicator_text"
        ),
        html.P(
            id = 'tweet_value',
            className="indicator_value"
        ),
    ],
    className="four columns indicator",

)

@app.callback(
Output("tweet_value","children")

)
def total_tweet_callback():

    return 100   

需要至少一个输入或事件才能调用回调,如 dash.py 代码中所写:

Without Input or Event elements, this callback will never get called.

(Subscribing to input components will cause the callback to be called whenever their values change and subscribing to an event will cause the callback to be called whenever the event is fired.)

在您的情况下 - 如果没有触发回调,为什么要使用回调?如果你希望 total_tweet_callback 到 运行 只加载一次,只需从布局中调用它:

def total_tweet_callback():
    return 100

app.layout = lambda: html.Div(
    [
        html.P(
            "Tweet Count",
            className="twelve columns indicator_text"
        ),
        html.P(
            children=total_tweet_callback(),
            id='tweet_value',
            className="indicator_value"
        ),
    ],
    className="four columns indicator",
)

注意:

  1. 我从 total_tweet_callback 中删除了装饰器。
  2. 我给布局一个 function(在本例中为 lambda 函数)returns Div 元素。这不一定是必需的,取决于代码的其他方面。例如,包含 lambda: 会导致每次重新加载页面时调用 total_tweet_callback 函数,而删除它只会在加载应用程序时获取一次值。

所有回调在加载时都是 运行 一次,除非明确禁用。所以一个简单的解决方案是使用虚拟输入,引用任何东西,而不是使用它。

我不同意其他答案。直接调用该函数不会使其每隔 'load' 触发一次。这样,当语句为 运行 时,函数仅 运行 一次。该功能仅在应用程序启动时触发,而不是每次单击浏览器的刷新按钮时触发。如果你在那里使用 datetime.datetime.now(),你可以看到区别。

您可以使用 dcc.Interval

刷新页面时有效。

from datetime import datetime

# within layout
dcc.Interval(
    id="load_interval", 
    n_intervals=0, 
    max_intervals=0, #<-- only run once
    interval=1
),
html.Span(
    id="spanner",
    style=dict(color="yellow") #<-- just so it's easy to see
),

# callback
@app.callback(
    Output(component_id="spanner", component_property="children"),
    Input(component_id="load_interval", component_property="n_intervals"),
)
def update_spanner(n_intervals:int):
    return datetime.now()

无论如何我都需要定期刷新初始数据所以熟悉Interval是件好事。 n_intervals 有点像 n_clicks.

https://dash.plotly.com/dash-core-components/interval


免责声明;我上面的方法是一种 hack,我不知道它是否会长期有效。