带有多个打开它的按钮的 Dash 模态

Dash modal with multiple buttons that open it

按照文档的这一部分:https://dash-bootstrap-components.opensource.faculty.ai/l/components/modal我在我的 Dash 应用程序中创建了一个模式。模式的触发器将动态呈现缩略图。单击其中任何一个时,模式应打开并显示缩略图中的图像作为其正文。

在 Dash 中,有可能有多个按钮(我不知道会有多少,取决于数据库中有多少缩略图),它们都将打开相同的模式对话框并传递他们的一些数据到模态(例如我的 img src)?

上面例子中的输入很简单:

[
    Input("open", "n_clicks"), Input("close", "n_clicks")
],

但实际上我不知道会有多少,也不能硬编码 ID。

有什么建议吗?

是的,您可以让多个按钮打开一个模式。正如您所展示的那样,回调将为每个回调都有一个 Input 。不,您不能动态创建它们。 Dash 不能很好地处理任何不在 运行 应用程序开始时布局中的 ID。

使用下面的列表理解动态创建一组按钮:

[dcc.Button(x, id={'type': 'thumbnail_button', 'index': x}) for x in thumbnail_list]

单击这些按钮中的任何一个时,使用模式匹配回调打开模式:

@app.callback(
              Output('your-modal', 'is_open'),
              [Input({'type': 'thumbnail_button', 'index': ALL}, 'n_clicks')]
)
def handle_button_click(n_clicks):

    invoker = [p['prop id'] for p in dash.callback_context.triggered][0]
    invoker_type = json.loads(invoker.split('.')[0])['type']
    invoker_index = json.loads(invoker.split('.')[0])['index']
    if invoker_type == "thumbnail_button":
        return not is_open
    else:
        return is_open

最后是进口:

from dash.dependencies import Input, Output, ALL