【问题标题】:How to add separate Html elements on a button click on Python Dash如何在单击 Python Dash 的按钮上添加单独的 Html 元素
【发布时间】:2020-04-14 14:50:29
【问题描述】:

我尝试使用 Python dash 实现的一个非常简单的场景。在每个按钮上添加相似的元素一个接一个地单击。

下面是代码。

app.layout = {
  html.Button(id='add-element-button', n_clicks=0, children='Add Input Element'),
  html.Div(id="layout")
}

@app.callback(Output('layout', 'children'),
              [Input('add-element-button', 'n_clicks')])
def add_strategy_divison(val):
    if val:
        return html.Div(id=f"heading_element_{val}",
            [
                html.H1(id=f"heading_{val}", children=f"{val} Heading"),
            ]
            )
    else:
        raise PreventUpdate

似乎正在发生的事情不是添加新元素,而是用新的标题元素和新的 id 覆盖第一个标题元素(在第一次点击时成功创建)。

有人知道会发生什么吗?谢谢!

【问题讨论】:

    标签: python python-3.x plotly plotly-dash plotly-python


    【解决方案1】:

    您描述的行为非常合理。您返回一个新的 div 元素,这意味着您覆盖了 layout 元素的 children 属性。这样,您将始终替换现有的孩子。

    要按您希望的方式工作,您需要获取 layout 元素的当前子元素并将新元素添加到其中。将当前子项作为 State 对象传递给您的回调。现在将您的元素附加到子元素并返回列表。

    @app.callback(
        Output('layout', 'children'),
        [Input('add-element-button', 'n_clicks')],
        [State('layout', 'children')],
    )
    def add_strategy_divison(val, children):
        if val:
            el = html.Div(id=f"heading_element_{val}", [
                html.H1(id=f"heading_{val}", children=f"{val} Heading"),
            ])
            children.append(el)
            return children
        else:
            raise PreventUpdate
    

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2019-05-19
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多