当某人更改下拉值时,我想更新数据表。我做了一些尝试,但似乎没有成功。以下是官方教程中的示例,但进行了细微修改。
(1)尝试1:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_table as dt
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': 'California', 'value': 'CA'},
{'label': 'Texas', 'value': 'TX'},
{'label': 'New York', 'value': 'NY'}],
value='CA'
),
dt.DataTable('data-table-1')
])
@app.callback(
Output('data-table-1', 'row'),
[Input('dropdown', 'value')]
)
def update_rows(selected_value):
data = df[df['State'] == selected_value]
columns = [{"name": i, "id": i} for i in data.columns]
return [dt.DataTable(data=data, columns=columns)]
if __name__ == '__main__':
app.run_server(debug=True)
错误消息说
Attempting to assign a callback to the
component with the id "data-table-1" but no
components with id "data-table-1" exist in the
app's layout.
Here is a list of IDs in layout: ['dropdown']
If you are assigning callbacks to components
that are generated by other callbacks
(and therefore not in the initial layout), then
you can suppress this exception by setting
`suppress_callback_exceptions=True`.
它说不存在ID为'data-table-1'的组件,我不知道为什么会发生这种情况。此ID“ data-table-1”位于app.layout中。
其次,它说要设置'suppress_callback_exceptions = True',因此下面是另一种尝试。
(2)尝试2:仅将一行代码添加到“尝试1”中
app.config['suppress_callback_exceptions'] = True
添加此行代码后,我可以运行该应用程序。但是当我转到仪表板时,它显示以下错误消息
Invalid argument `active_cell` passed into DataTable.
Expected `object`.
Was supplied type `string`.
Value provided: "data-table-1"
有人可以帮我吗?谢谢。
答案 0 :(得分:1)
第一个示例中的问题是您只是没有足够的ID分配权限。这就是您需要的:
app.layout = html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': 'California', 'value': 'CA'},
{'label': 'Texas', 'value': 'TX'},
{'label': 'New York', 'value': 'NY'}],
value='CA'
),
dt.DataTable(id='data-table-1')
])