如何根据选定的下拉值在 Dash DataTable 中动态添加列

How to dynamically add columns in Dash DataTable based on selected dropdown values

我想使用 Dash 根据选定的下拉列表值在 DataTable 中动态添加列。 我的 table 也是基于两个下拉列表动态创建的(我有一个 returns 整个 DataTable 定义的回调)。

我尝试了 Adding or removing columns 部分中的示例,但它仅在您尝试使用按钮添加列时有效。

这是我添加列的代码:

@app.callback(
[Output(‘main_table’, ‘columns’)],
[Input(‘second_dropdown’, ‘value’)],
[State(‘main_data’, ‘data’), State(‘main_table’, ‘columns’)]
)
def add_columns(values, data, existing_columns):
if existing_columns is None:
return None
for value in values:
if value not in existing_columns:
existing_columns.append({
‘id’: value,
‘name’: value
})
print(existing_columns)
return existing_columns

'main_data' 存储在 json 文件中,该文件包含在第二个下拉列表中的值更改时应显示的数据。 结果我希望有一个 table 哪些列是所选下拉值的数量。

我是 Dash 的新手,所以如果有人能帮助我,我将不胜感激。

如果有人也有同样的问题,这里是解决方案(非常感谢Marc-Andre):

import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate

from dash_table import DataTable, FormatTemplate
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Dropdown(
        id='dropdown',
        options=[{
            'label': 'label: ' + id,
            'value': id
        } for id in ['b', 'c', 'd', 'e', 'f']]
    ),
    DataTable(
        id='table',
        columns=[{
            'name': x,
            'id': x,
            'selectable': True
        } for x in ['a']],
        column_selectable="single",
        data=[{
            'a': 'a' + str(x),
            'b': 'b' + str(x),
            'c': 'c' + str(x),
            'd': 'd' + str(x),
            'e': 'e' + str(x),
            'f': 'f' + str(x)
        } for x in range(0,100)]
    )
])

@app.callback(
    Output('table', 'columns'),
    [Input('dropdown', 'value')],
    [State('table', 'columns')]
)
def update_columns(value, columns):
    if value is None or columns is None:
        raise PreventUpdate

    inColumns = any(c.get('id') == value for c in columns)

    if inColumns == True:
        raise PreventUpdate

    columns.append({
        'label': 'label: ' + value,
        'id': value
    })
    return columns

if __name__ == '__main__':
    app.run_server(debug=False)