Plotly Dash 回调错误:试图隐藏 Div 组件

Posted

技术标签:

【中文标题】Plotly Dash 回调错误:试图隐藏 Div 组件【英文标题】:Plotly Dash Callback error : Trying to hide Div components 【发布时间】:2021-08-13 02:13:36 【问题描述】:

我试图在点击链接后隐藏输入组件Div

我已经给出了 Div id='input_fields',以便我可以隐藏它的子组件,但在 return app1.layout, 'display': 'none' 上我收到以下错误。

“回调错误更新display-page.children, input_fields.children”

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Br(),
    html.H1("Interpretation of Financial Statements", style='text-align': 'center'),
    html.H1("10 year data analysis", style='text-align': 'center'),
    html.Div([dcc.Input(id='input-1-state', type='text', placeholder="Enter Company Ticker", value=''),
              dcc.Input(id='input-2-state', type='text', placeholder="Enter Company Name", value=''),
              dcc.Link(' Get Analytics ', href='/apps/app1')], id='input_fields'),
    html.Div(id='display-page'),

], style="margin-left": "5%", "margin-right": "5%")


@app.callback(Output('display-page', 'children'),
              Output('input_fields', 'children'),
              [Input('url', 'pathname')],
              Input(component_id='input-1-state', component_property='value'),
              Input(component_id='input-2-state', component_property='value'))
def display_page(pathname, ticker, company):
    if pathname == '/apps/app1':

        # generate links
        linkGenerator.generateLinks(ticker, company)

        # starting crawler
        startingCrawlerClass()

        return app1.layout, 'display': 'none'
    else:
        return ''

【问题讨论】:

【参考方案1】:

问题在于回调中else 子句的return 语句。您的回调需要两个回调输出,但您返回一个(即单个空字符串)。

如果您在调试模式下运行应用程序,Dash 会告诉您这一点以及它希望您返回的内容:

dash.exceptions.InvalidCallbackReturnValue:回调 ..display-page.children...input_fields.children.. 是一个多输出。 期望输出类型是列表或元组,但得到:''。

所以你可以这样做:

@app.callback(
    Output("display-page", "children"),
    Output("input_fields", "style"),
    [Input("url", "pathname")],
    Input(component_id="input-1-state", component_property="value"),
    Input(component_id="input-2-state", component_property="value"),
)
def display_page(pathname, ticker, company):
    if pathname == "/apps/app1":
        return app1.layout, "display": "none"
    else:
        return '', 'display': 'block'

所以上面的例子返回了一个包含两个元素的元组。每个元素对应一个回调输出。 input-field 的输出也是 style

【讨论】:

哦,我没有注意到,我也缺少输入字段的组件属性,在你的答案中进行了调整。感谢您的回答,非常感谢:)

以上是关于Plotly Dash 回调错误:试图隐藏 Div 组件的主要内容,如果未能解决你的问题,请参考以下文章

Plotly Dash 表回调

Plotly Dash:下拉组件回调可见性错误

如何为下拉菜单修复 plotly-dash 中的“回调错误”

Plotly Dash 回调错误更新输出图

Plotly Dash dcc.Interval 在一段时间后失败:回调错误更新 graph.figure

Dash Plotly中的烛台图和折线图,它会随着回调而更新,但会消失