如何为生成的组件创建动态回调

Iva*_*van 5 plotly-dash

我能够理解如何callbacks在工作dash-table-experiment,其中DataTable的部分app.layout = Div/Html layout

但是如何创建这样callbackDataTable生成时间并且它不是静态布局的一部分?

def generate_table(tdf, max_rows=200):
    return  dt.DataTable(rows=tdf.to_dict('records'),
             columns=tdf.columns,
             row_selectable=True,
             filterable=False,
             sortable=False,
             selected_row_indices=[],
             id="datatable-gapminder"
            )
Run Code Online (Sandbox Code Playgroud)

如果我说

@app.callback(
    Output('datatable-gapminder', 'selected_row_indices'),
    [Input('graph-gapminder', 'clickData')],
    [State('datatable-gapminder', 'selected_row_indices')])
def update_selected_row_indices(clickData, selected_row_indices):
    if clickData:
        for point in clickData['points']:
            if point['pointNumber'] in selected_row_indices:
                selected_row_indices.remove(point['pointNumber'])
            else:
                selected_row_indices.append(point['pointNumber'])
    return selected_row_indices
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

Attempting to assign a callback to the
component with the id "datatable-gapminder" but no
components with id "datatable-gapminder" exist in the
app's layout.
Run Code Online (Sandbox Code Playgroud)

jac*_*dbd 5

您收到该错误是因为带有 id 的组件datatable-gapminder尚未在布局中。

如果要为尚未在布局中的组件创建回调,则必须抑制回调异常。

app.config.supress_callback_exceptions = True
Run Code Online (Sandbox Code Playgroud)

我认为您还需要一个功能来为布局提供服务。默认情况下,Dash 应用程序将 存储app.layout在内存中。如果您将 app.layout 设置为一个函数,那么您可以在每次页面加载时提供动态布局。见这里

def serve_layout():
    layout = html.Div(
        children=[
            # dt.DataTable()
        ],
    )
    return layout

app.layout = serve_layout
Run Code Online (Sandbox Code Playgroud)