Dash - 间隔不调用回调
Dash - Interval not invoking callback
我正在使用 Dash - Plot.ly 创建仪表板,我需要定期更新。我找到了应该完成这项工作的 dcc.Interval()
组件,但发生了奇怪的行为。如果代码正确,回调只会被调用一次,如果代码中有错误,比如引用了一个不存在的变量,就会出现循环行为。知道哪里出了问题吗?
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout=html.Div([dcc.Interval(id='interval-component',
interval=1*1000, n_intervals=0)], id="acoolId")
@app.callback(
Output('acoolId', 'children'),
[Input('interval-component', 'n_intervals')])
def timer(n):
# print(asdlol) # if this line is enabled, the periodic behavior happens
return [html.P("ASD " + str(n))]
if __name__ == '__main__':
app.run_server(debug=True)
问题是您的回调正在用 ID "acoolID"
替换元素的 children
,这就是您的 interval
组件所在的位置。因此,回调触发一次,并替换回调的输入,使其无法再次触发。
将您的布局更改为类似这样的内容,以便您更新的 children
是一个不同的组件:
app.layout = html.Div(
children=[
dcc.Interval(id='interval-component',
interval=1 * 1000,
n_intervals=0),
html.Div(id="acoolId", children=[]),
]
)
我已经测试过了,回调现在可以正常工作了。
我正在使用 Dash - Plot.ly 创建仪表板,我需要定期更新。我找到了应该完成这项工作的 dcc.Interval()
组件,但发生了奇怪的行为。如果代码正确,回调只会被调用一次,如果代码中有错误,比如引用了一个不存在的变量,就会出现循环行为。知道哪里出了问题吗?
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
from dash.dependencies import Input, Output
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout=html.Div([dcc.Interval(id='interval-component',
interval=1*1000, n_intervals=0)], id="acoolId")
@app.callback(
Output('acoolId', 'children'),
[Input('interval-component', 'n_intervals')])
def timer(n):
# print(asdlol) # if this line is enabled, the periodic behavior happens
return [html.P("ASD " + str(n))]
if __name__ == '__main__':
app.run_server(debug=True)
问题是您的回调正在用 ID "acoolID"
替换元素的 children
,这就是您的 interval
组件所在的位置。因此,回调触发一次,并替换回调的输入,使其无法再次触发。
将您的布局更改为类似这样的内容,以便您更新的 children
是一个不同的组件:
app.layout = html.Div(
children=[
dcc.Interval(id='interval-component',
interval=1 * 1000,
n_intervals=0),
html.Div(id="acoolId", children=[]),
]
)
我已经测试过了,回调现在可以正常工作了。