python - 带回调的 Plotly Dash 实时更新引发 LayoutIsNotDefined 异常

标签 python plotly-dash

我按照 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`

最佳答案

这段代码对我有用:

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)

Dash page

以下是我用来引用的软件包版本:

# 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

关于python - 带回调的 Plotly Dash 实时更新引发 LayoutIsNotDefined 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61412072/

相关文章:

python - mysql wheel 在此平台上不支持 wheel

python - 防止无限回调循环部署带有 Gunicorn 的 Dash 应用程序,其中存在 `dcc.Interval` 和 `dcc.Location`(即多页应用程序)组件

python - Plotly-Dash Graph - 显示在形状后面的文本注释

python - python的plotly和dash的依赖问题

python - 一起运行两个 Python 应用程序?

plotly-dash - 带有全选复选框的破折号数据表?

python - PyInstaller,使模块像普通 Python 一样不可导入

用于自定义类型的 python sqlite3 适配器

javascript - Django /jQuery : handling template inheritence and JS files loading

python - 从Python中的SQL查询中选择时间戳