如何在Plotly Dash AG Grid中基于可编辑单元格更新单个单元格值?
问题:Dash AG Grid编辑列B后自动更新对应行的列D为40?
我是Plotly Dash和AG Grid的新手,目前正在用Dash创建AG Grid,希望在可编辑列B的单元格内容被修改时,将对应行的列D单元格值更新为40。以下是我的代码实现,请求指导:
curves_grid = dash.Dash(__name__, external_stylesheets=[dbc.themes.LITERA]) # Define the layout of the app gbp_curves_grid.layout = html.Div([ dag.AgGrid( id='curves_grid', columnDefs=[ {'field': 'A', 'editable': False}, {'field': 'B', 'editable': True}, {'field': 'C', 'editable': False, "cellRenderer": "agAnimateShowChangeCellRenderer"}, {'field': 'D', 'editable': False}, ], rowData=df_curves.to_dict("records"), enableEnterpriseModules=True, getRowId="params.data.id", ), ]) @curves_grid.callback(Output('curves_grid', 'rowTransaction'), Input('curves_grid', 'cellValueChanged'), prevent_initial_call=True,) def update_close(row_changed): if row_changed: row_changed[0]['data']['D'] = 40 return {"update": row_changed}
修正方案:
你的代码有几个关键问题需要调整,以下是修复后的完整代码:
import dash import dash_ag_grid as dag import dash_bootstrap_components as dbc from dash import html # 初始化Dash应用,统一变量名 curves_grid = dash.Dash(__name__, external_stylesheets=[dbc.themes.LITERA]) # 假设df_curves是你的数据源,确保每行包含唯一的'id'字段 # df_curves = ... curves_grid.layout = html.Div([ dag.AgGrid( id='curves_grid', columnDefs=[ {'field': 'A', 'editable': False}, {'field': 'B', 'editable': True}, {'field': 'C', 'editable': False, "cellRenderer": "agAnimateShowChangeCellRenderer"}, {'field': 'D', 'editable': False}, ], rowData=df_curves.to_dict("records"), enableEnterpriseModules=True, getRowId="params.data.id", ), ]) @curves_grid.callback( Output('curves_grid', 'rowTransaction'), Input('curves_grid', 'cellValueChanged'), prevent_initial_call=True, ) def update_close(cell_change): # cellValueChanged返回单个修改事件对象,直接取其中的data字段 if cell_change: modified_row = cell_change['data'] # 更新D列的值为40 modified_row['D'] = 40 # 返回rowTransaction,update接收包含修改后行的列表 return {"update": [modified_row]} # 无修改时返回空字典 return {} if __name__ == '__main__': curves_grid.run_server(debug=True)
关键修改点:
- 统一变量名:原代码中应用实例是
curves_grid,但布局赋值给了gbp_curves_grid.layout,这会导致布局无法加载,需统一为curves_grid.layout。 - 正确处理cellValueChanged结构:
cellValueChanged事件返回的是单个字典,不是列表,无需用row_changed[0],直接访问cell_change['data']即可获取修改后的行数据。 - 正确构造rowTransaction:
rowTransaction的update字段需要接收包含修改后行对象的列表,而非单个对象。 - 添加启动代码:补充
if __name__ == '__main__'块,确保应用可以正常运行。
修改后,编辑列B的单元格时,对应行的D列会自动更新为40。
内容的提问来源于stack exchange,提问作者lgds
相关产品推荐
相关产品推荐

