数据表下拉选项更新回调输出函数

huangapple go评论77阅读模式
英文:

DataTable dropdown option update callback output function

问题

# 更新后的代码

import dash
from dash import Dash, dash_table, dcc, html, Input, Output, State, no_update, callback
import dash_bootstrap_components as dbc
import pandas as pd

app = dash.Dash(__name__)

# 创建一个示例 DataFrame
df = pd.DataFrame({'TeamID': [1, 2, 3, 4],
                   'TeamName': ['Team 1', 'Team 2', 'Team 3', 'Team 4'],
                   'Finished': [1, 1, 0, 1]})

team_select_table = dash_table.DataTable(
    id='team-selection-table',
    editable=True,
    column_selectable="single",
    row_selectable="multi",
    row_deletable=False,
    selected_columns=[],
    page_action="native",
    page_current=0,
    page_size=100,
    style_table={'minWidth': '100%'},
    dropdown={},

    style_header={
        'backgroundColor': 'rgb(30, 30, 30)',
        'color': 'white',
        'fontWeight': 'bold',
        'textAlign': 'center'
    },
    style_data={
        'whiteSpace': 'normal',
        'backgroundColor': 'rgb(50, 50, 50)',
        'color': 'white'
    },
    style_data_conditional=[
        {'if': {'column_id': 'TeamID'},
         'width': '10%'},
        {'if': {'column_id': 'TeamName'},
         'width': '10%'},
    ],
    style_cell_conditional=[
        {
            'if': {'column_id': c},
            'textAlign': 'center'
        } for c in ['TeamID', 'TeamName']
    ],
)

app.layout = html.Div([
    team_select_table,
    html.Div(id='dummy_div'),
])

@app.callback(
    Output('team-selection-table', 'data'),
    Output('team-selection-table', 'columns'),
    Output('team-selection-table', 'dropdown'),
    Output('team-selection-table', 'style_data_conditional'),
    Input('dummy_div', 'children'),
    prevent_initial_call=False,
    background=False,
)
def load_teams(dummy):
    df['Finished'] = df['Finished'].map({1: True, 0: False})  # 转换为布尔值

    df_columns = [{'name': col, 'id': col} for col in df.columns]
    df_data = df.to_dict(orient='records')

    dropdown = {
        'TeamID': {'options': [{'label': str(val), 'value': val} for val in df['TeamID'].unique()]},
        'Finished': {'options': [{'label': '是', 'value': True}, {'label': '否', 'value': False}]}
    }

    style_data_conditional = [
        {
            'if': {'column_id': 'Finished'},
            'presentation': 'dropdown'
        }
    ]

    return df_data, df_columns, dropdown, style_data_conditional

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8020, debug=True)
英文:

UPDATED CODE

import dash
from dash import Dash, dash_table, dcc, html, Input, Output, State, no_update, callback
import dash_bootstrap_components as dbc
import pandas as pd
app = dash.Dash(__name__)
# Create a sample DataFrame
df = pd.DataFrame({'TeamID': [1, 2, 3, 4],
'TeamName': ['Team 1', 'Team 2', 'Team 3', 'Team 4'],
'Finished': [1,1,0,1]})
team_select_table = dash_table.DataTable(
id='team-selection-table',
editable=True,
column_selectable="single",
row_selectable="multi",
row_deletable=False,
selected_columns=[],
page_action="native",
page_current= 0,
page_size= 100,
style_table={'minWidth': '100%'},
dropdown={},
style_header={
'backgroundColor': 'rgb(30, 30, 30)',
'color': 'white',
'fontWeight': 'bold',
'textAlign': 'center'
},
style_data={
'whiteSpace': 'normal',
'backgroundColor': 'rgb(50, 50, 50)',
'color': 'white'
},
style_data_conditional=[
{'if': {'column_id': 'TeamID'},
'width': '10%'},
{'if': {'column_id': 'TeamName'},
'width': '10%'},
],
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'center'
} for c in ['TeamID', 'TeamName']
],
)
app.layout = html.Div([
team_select_table,
html.Div(id='dummy_div'),
])
@app.callback(
Output('team-selection-table', 'data'),
Output('team-selection-table', 'columns'),
Output('team-selection-table', 'dropdown'),
Output('team-selection-table', 'style_data_conditional'),
Input('dummy_div', 'children'),
prevent_initial_call=False,
background=False,
)
def load_teams(dummy):
df['Finished'] = df['Finished'].map({1: True, 0: False})  # Convert to boolean values
df_columns = [{'name': col, 'id': col} for col in df.columns]
df_data = df.to_dict(orient='records')
dropdown = {
'TeamID': {'options': [{'label': str(val), 'value': val} for val in df['TeamID'].unique()]},
'Finished': {'options': [{'label': 'Yes', 'value': True}, {'label': 'No', 'value': False}]}
}
style_data_conditional = [
{
'if': {'column_id': 'Finished'},
'presentation': 'dropdown'
}
]
return df_data, df_columns, dropdown, style_data_conditional
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8020,debug=True)

Given the code above, I've been trying to update the dropdown options inside the datatable for the 'Finished' column. I cannot find an example online of someone doing this but following the references for the datatable, it should be possible. Could someone shed some light on what I'm missing? I've got more code involved but these are the primary pieces that I am having issues with.

答案1

得分: 1

有多个问题。

1 在回调中引用了 dummy_div,但是这个元素在应用的布局中不存在。

2DataTable 上设置了 editableFalse。下拉菜单用于编辑,因此如果在数据表上禁用编辑,就不能使用它们。

3 在回调中你这样做:

dropdown = {
    "Finished": {"options": [{"label": i, "value": i} for i in df["Finished"].unique()]}
}

return dropdown

如果你在调试模式下运行应用,Dash 会告诉你:
> 传递给 ID 为 "team-selection-table" 的 DataTable 的无效参数 dropdown.Finished.options[0].label
期望是 string 类型。
提供的是 boolean 类型。

df["Finished"] 包含布尔值,因此在将它们作为标签传递之前,将这些值转换为字符串。

4 你没有在 DataTable 上设置 datacolumn 属性:

# 添加这些
columns=[{"name": column, "id": column, "presentation": "dropdown"} for column in df.columns],
data=df.to_dict('records'),

请注意使用了 presentation": "dropdown"。在上面的片段中,我对所有列都设置了 presentation": "dropdown",但在你的情况下,你可以调整列表推导式,仅对 Finished 列使用这个设置。

英文:

There are multiple problems.

1 You reference dummy_div in your callback, but this element doesn't exist in the app's layout.

2 You set editable on the DataTable to False. Dropdowns are for editing so you can't have them if you've disabled editing on the datatable.

3 In your callback you do this:

dropdown = {
"Finished": {"options": [{"label": i, "value": i} for i in df["Finished"].unique()]}
}
return dropdown

If you run the app under debug Dash will tell you:
> Invalid argument dropdown.Finished.options[0].label passed into DataTable with ID "team-selection-table".
Expected string.
Was supplied type boolean.

df["Finished"] contains boolean values so convert the values to strings before you pass them as labels.

4 You don't set data and column properties on the DataTable:

# Add these
columns=[{"name": column, "id": column, "presentation": "dropdown"} for column in df.columns],
data=df.to_dict('records'),

Note the use of "presentation": "dropdown". I'm lazy in the snippet above in that I set "presentation": "dropdown" for all columns. In your case you can adjust the list comprehension to only use this for the "Finished" column.

huangapple
  • 本文由 发表于 2023年7月7日 03:23:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定