Python 在另一个回调中使用返回的dash datatable
我在Dash中有一个表单,它接受值并基于该值返回一个过滤数据表:Python 在另一个回调中使用返回的dash datatable,python,callback,plotly-dash,Python,Callback,Plotly Dash,我在Dash中有一个表单,它接受值并基于该值返回一个过滤数据表: import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import pandas as pd from dash.dependencies import Input, Output import dash_table import numpy
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from dash.dependencies import Input, Output
import dash_table
import numpy as np
df = pd.DataFrame(np.random.randint(10, size=[100,4]), columns=set('ABCD'))
print(df)
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
controls = dbc.Card(
[
dbc.FormGroup(
[
dbc.Label("Select group"),
dbc.Input(id="group", type="number", value=3),
]
),
html.Div(id='my_output'),
html.Div(id='s_rows')
],
body=True,
)
app.layout = dbc.Container(
[
dbc.Row(
[
dbc.Col(controls, md=4),
],
align="center",
),
],
fluid=True,
)
@app.callback(
Output('my_output', 'children'),
[
Input("group", "value"),
],
)
def filtered_data(group):
data = df[df['D'] == group]
return dash_table.DataTable(
style_cell={
'whiteSpace': 'normal',
'height': 'auto',
},
id='table',
columns=[
{"name": i, "id": i, "deletable": True, "selectable": True} for i in data.columns
],
data=data.to_dict('records'),
editable=True,
filter_action="native",
sort_action="native",
sort_mode="multi",
row_selectable="multi",
selected_columns=[],
selected_rows=[],
page_action="native",
page_current=0
)
@app.callback(
Output('s_rows', 'children'),
[
Input('table', 'selected_rows'),
]
)
def get_checked(selected_rows):
return selected_rows
if __name__ == "__main__":
app.run_server(debug=True, port=8000)
正如您在第一个回调函数中看到的,该函数返回过滤后的数据表,其中包含一个供用户选择行的选项
我希望能够将所选行传递到另一个回调中,但Dash无法识别我为返回的datatable设置的ID,从而导致错误:
ID not found in layout
Attempting to connect a callback Input item to component:
"table"
but no components with that id exist in the layout.
由于应用程序运行时未立即定义
选定的\u行
,因此会出现一个错误,即布局中不存在具有该id的组件,因为该组件尚未定义。如果您还更仔细地观察错误,在错误的结尾,它还说,如果将回调分配给由其他回调生成的组件(因此不在初始布局中)
,则通过设置suppress\u callback\u exceptions=True来抑制此异常
因此,您只需在应用程序的定义中添加suppress\u callback\u exceptions
:
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)