首页 > 解决方案 > 带有回调的 Plotly Dash 实时更新引发 LayoutIsNotDefined 异常

问题描述

我正在按照 Dash 网站上的指南在页面刷新时进行实时更新:

import datetime

import dash
import dash_html_components as html

def serve_layout():
    return html.Div([
        dcc.Interval(id="time_trigger", interval=1000),
        html.H1('The time is: ' + str(datetime.datetime.now()), id="header")])

app.layout = serve_layout

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

但是,这确实适用于回调。如果我执行以下操作,则会引发 LayoutIsNotDefined:

@app.callback(
    Output("header", "children"),
    [Input("time_trigger", "n_intervals")]
)
def connect_to_date_sync_service(n_interval):
    return "Interval is triggered {} times".format(n_interval)

这是 Dash 引发的错误:

dash.exceptions.LayoutIsNotDefined: 
Attempting to assign a callback to the application but
the `layout` property has not been assigned.
Assign the `layout` property before assigning callbacks.
Alternatively, suppress this warning by setting
`suppress_callback_exceptions=True`

标签: pythonplotly-dash

解决方案


这段代码对我有用:

import datetime
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash()

def serve_layout():
    return html.Div([
        dcc.Interval(id="time_trigger", interval=1000),
        html.H1('The time is: ' + str(datetime.datetime.now()), id="header")])

app.layout = serve_layout


@app.callback(
    Output("header", "children"),
    [Input("time_trigger", "n_intervals")]
)
def connect_to_date_sync_service(n_interval):
    return "Interval is triggered {} times".format(n_interval)

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

仪表板页面

以下是我用作参考的软件包版本:

# Name                    Version                   Build  Channel
dash                      1.11.0             pyh9f0ad1d_0    conda-forge
dash-bootstrap-components 0.9.2              pyh9f0ad1d_0    conda-forge
dash-core-components      1.9.1              pyh9f0ad1d_0    conda-forge
dash-daq                  0.4.0                      py_0    conda-forge
dash-html-components      1.0.3              pyh9f0ad1d_0    conda-forge
dash-renderer             1.4.0              pyh9f0ad1d_0    conda-forge
dash-table                4.6.2              pyh9f0ad1d_0    conda-forge

推荐阅读