如何在Dash的HTML容器中嵌入显示DataTable表格
问题根因
- 表格无法渲染:代码中两次对
app.layout赋值,第二次赋值的外层html.Div完全覆盖了第一次赋值的DataTable组件,最终页面只会渲染最后一次定义的布局结构,独立测试文件中仅将DataTable设为layout因此可正常运行。同时代码重复执行了两次app = Dash(__name__)实例化,会导致组件注册状态异常。另外两处DataFrame定义共用df变量名,后定义的表格数据会覆盖前序图表使用的水果数据,导致图表渲染异常。 - 语法报错:将表格代码移入容器时,误将顶层的变量赋值语句(如
data = OrderedDict(...))直接写在了children参数的列表内部,children仅接受Dash组件实例、字符串、数字等可渲染内容,不支持赋值表达式,Python解析时会直接抛出语法错误。 - 额外冗余问题:
fig.update_layout()代码块末尾多写了一个逗号,会将布局配置返回值转为元组,虽不直接报错但属于无效写法。
修复方案
- 全文件仅保留一次
app = Dash(__name__)实例化语句,删除重复的实例化代码。 - 所有数据预处理逻辑(OrderedDict定义、表格DataFrame生成)全部放在代码顶层,不要嵌套到组件参数内部。将表格使用的DataFrame重命名为
df_table,避免和图表使用的df变量冲突。 - 移除第一次将DataTable直接赋值给
app.layout的代码,将DataTable组件移入class为graphique3的容器children中。 - 删除
fig.update_layout()末尾多余的逗号。
修复后完整代码
# Run this app with `python app.py` and # visit http://127.0.0.1:8050/ in your web browser. from dash import Dash, html, dcc, dash_table import plotly.express as px import pandas as pd import dash_daq as daq from collections import OrderedDict app = Dash(__name__) # 柱状图数据 df = pd.DataFrame({ "Fruit": ["Apples", "Oranges", "Bananas", "test4", "test5", "test6","test7","test8","test9"], "Amount": [4, 1, 2, 2, 4, 5, 9, 5, 6], }) fig = px.bar(df, x="Fruit", y="Amount", barmode="group") # 调整图表边距 fig.update_layout( margin=dict(l=5, r=5, t=5, b=5), paper_bgcolor="white" ) # 表格数据 data = OrderedDict( [ ("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]), ("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]), ("Temperature", [1, -20, 3.512, 4, 10423, -441.2]), ("Humidity", [10, 20, 30, 40, 50, 60]), ("Pressure", [2, 10924, 3912, -10, 3591.2, 15]), ] ) df_table = pd.DataFrame(data) app.layout = html.Div(className='dashboard', children=[ # 第一行图表 html.Div(className='row1', style={'display': 'flex', 'justify-content': 'center'}, children=[ html.Div(className='graphique1',children=[ dcc.Graph( id='exemple-graph1', figure=fig, style={'flex-grow': '1', 'width':'900px'} ), ]), html.Div(className='graphique2',children=[ dcc.Graph( id='exemple-graph2', figure=fig, style={'flex-grow': '1', 'width':'900px'} ), ]), ]), # 第二行图表 html.Div(className='row2', style={'display': 'flex', 'justify-content': 'center'}, children=[ # 表格放在graphique3容器内 html.Div(className='graphique3', children=[ dash_table.DataTable( data=df_table.to_dict('records'), columns=[{'id': c, 'name': c} for c in df_table.columns], style_cell_conditional=[ { 'if': {'column_id': c}, 'textAlign': 'left' } for c in ['Date', 'Region'] ], style_data={ 'color': 'black', 'backgroundColor': 'white' }, style_data_conditional=[ { 'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(220, 220, 220)', } ], style_header={ 'backgroundColor': 'rgb(210, 210, 210)', 'color': 'black', 'fontWeight': 'bold' } ) ]), html.Div(className='graphique4', children=[ daq.Gauge( color={"gradient": True, "ranges": {"green": [0, 6], "yellow": [6, 8], "red": [8, 10]}}, value=2, label='Temps avant la prochaine relève', max=10, min=0, ), ]), html.Div(className='graphique5', children=[ dcc.Graph( id='exemple-graph5', figure=fig, ) ]), ]), ]) if __name__ == '__main__': app.run_server(debug=True)
内容的提问来源于stack exchange,提问作者Stacky
相关产品推荐
相关产品推荐

