我正在寻找一种解决方案,从动态添加到 Div 的按钮获取事件触发器,并在单独的回调中使用这些按钮 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
注意:使用
需要Dash 2.4+ctx.triggered_id
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)