使用模式匹配回调处理 Plotly Dash 中动态生成的组件

问题描述 投票:0回答:1

我正在寻找一种解决方案,从动态添加到 Div 容器的按钮获取事件触发器。如何在单个回调中使用这些按钮 ID(即,可以处理通过应用程序中的用户创建而存在的任意数量的动态生成的 ID 的回调)?

@app.callback(
        Output('button-container', 'children'),
        Input({'type': 'button', 'index': 'all'}, 'n_clicks'),
        State('button-container', 'children')
    )
    def update_button_text(n_clicks_list, button_children):
        ctx = dash.callback_context
        if not ctx.triggered:
            return button_children
        else:
            for i, button in enumerate(button_children):
                button_id = button['props']['id']
                n_clicks = n_clicks_list[i]['n_clicks']
                if button_id in ctx.triggered[0]['prop_id']:
                    button['props']['children'] = f'Button {n_clicks} clicked'
            return button_children
python callback plotly-dash
1个回答
0
投票

这是在 Python Plotly Dash 应用程序中使用模式匹配回调功能的示例:

注意:使用

ctx.triggered_id

需要Dash 2.4+
import dash
from dash import dcc, html, ctx
from dash import Dash, State, Input, Output, ALL, callback
from dash.exceptions import PreventUpdate

app = dash.Dash(__name__)


app.layout = html.Div(
    [
        html.H1(
            "Plotly Dash - After adding buttons to html.Div() via callback"
            ", how can we use these buttons as input to other callback"
        ),
        html.Div(
            [
                html.Button(
                    f"Button {i}",
                    id={"type": "pattern-matched-button", "index": i},
                )
                for i in range(1, 6)  # Create 5 button components
            ]
        ),
        html.Br(),
        html.Div(
            id="buttons-response",
            children=[html.H2("No buttons clicked yet.")],
        ),
    ],
    style={"textAlign": "center"},
)


@callback(
    Output("buttons-response", "children"),
    Input({"type": "pattern-matched-button", "index": ALL}, "n_clicks"),
)
def display_output(button_clicks):
    if len(button_clicks) < 1:
        raise PreventUpdate
    n_clicks = ctx.triggered[0]["value"]
    if not n_clicks:
        raise PreventUpdate
    button_id = ctx.triggered_id.index
    return html.Div(
        [html.H2(f"Button {button_id} clicked {n_clicks} times.")]
    )


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

它提供以下应用程序功能:

© www.soinside.com 2019 - 2024. All rights reserved.