代码之家  ›  专栏  ›  技术社区  ›  Soerendip

Plotly/Dash:如何防止动态插入的链接/元素在没有用户单击的情况下自动触发回调?

  •  0
  • Soerendip  · 技术社区  · 4 年前

    [ html.A(id=_id, children=html.Img(src=src, height=300, id=image_id, style={'margin': '10px'})) ,... ]

    动态地插入到Div中。当列表生成时,“单击”的第一个图像回调将触发。 然后强制另一个元素加载一些内容。用户现在可以更改或删除更新缩略图的图像。但是,第一个图像会再次发出一个单击。问题是图像从未被点击,现在强制其他元素加载完全错误的内容。有没有可能防止这种情况发生?

    我试过了

        @app.callback(
            Output('pko-image-clicked-output', 'children'),
            [Input({'type': 'image', 'index': ALL}, 'n_clicks')],
            prevent_initial_call=True
            )
        def pko_image_clicked(ndx):
            if ndx is None or len(ndx)==0: raise PreventUpdate
            ctx = dash.callback_context
            clicked = ctx.triggered[0]['prop_id']
            clicked = clicked.replace('{"index":"', '')
            clicked = clicked.split('","type":')[0].replace('\\', '')
            print('Clicked:', clicked)
            return clicked
    

    但没用。我有一个多页应用程序,需要:

    app.config['suppress_callback_exceptions'] = True
    
    

    此组件完成后,将激活(触发第一个映像的回调):

    def callbacks(app, fsc, cache):
            
        @app.callback(
        Output('pko-dropdown', 'options'),
        Input('tab', 'value'),
        Input('pko-delete-output', 'children'),
        State('wdir', 'children'),
        State('pko-dropdown', 'options'),
        )
        def pko_controls(tab, peak_deleted, wdir, old_options):
            if tab != 'pko':
                raise PreventUpdate
            peaklist = T.get_peaklist( wdir )
            if peaklist is None:
                raise PreventUpdate
            options = [{'label':label, 'value': i} for i, label in enumerate(peaklist.index)]
            if options == old_options:
                raise PreventUpdate
            return options
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   coralvanda    4 年前

    我不确定 ndx 是字符串。你用的是 ALL n_click int s。你可以尝试两件事。

    if not any(ndx):
        raise PreventUpdate
    

    如果这不起作用,你也可以:

    if len(dash.callback_context.triggered[0]) > 1:
        raise PreventUpdate
    

    我不得不处理同样的问题,所以我认为其中一个至少应该起作用。如果不行就告诉我。