You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多页面Dash应用中Dash Table回调不触发问题求助

解决多页面Dash应用中Dash Table回调不触发的问题

问题根源

你的代码核心错误在于:dash_table.py中重复创建了dash.Dash实例,导致表格的回调被绑定到这个独立的子应用上,而主应用(index.py中的app)并未加载这些回调。当主应用切换到/Gestion_CV页面时,表格组件能正常渲染,但回调和主应用完全无关,因此无法触发。

修复步骤

1. 修改dash_table.py,移除独立app实例并导出回调注册函数

import dash
from dash import dash_table, dcc, html
from dash.dependencies import Input, Output
import pandas as pd
import dash_bootstrap_components as dbc
from navbar import Navbar

nav = Navbar()

df = pd.read_csv('https://git.io/Juf1t')

body = dbc.Container([
    dbc.Label('Click a cell in the table:'),
    # 修复字符串转义错误,将\"替换为"
    dash_table.DataTable(df.to_dict('records'),[{"name": i, "id": i} for i in df.columns], id='tbl'),
    dbc.Alert(id='tbl_out'),
])

# 定义回调注册函数,接收主app作为参数
def register_callbacks(app):
    @app.callback(Output('tbl_out', 'children'), 
                  Input('tbl', 'active_cell'))
    def update_graphs(active_cell):
        return str(active_cell) if active_cell else "Click the table"


def main_Table():
    layout = html.Div([
        nav,
        body
    ])
    return layout

2. 修改index.py,注册子模块的回调

import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from homepage import Homepage
from resumen_comunal import Resumen_Comunal
# 导入子模块的布局函数和回调注册函数
from dash_main_table import main_Table, register_callbacks

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])

app.config.suppress_callback_exceptions = True

# 将子模块的回调注册到主app上
register_callbacks(app)

app.layout = html.Div([
    dcc.Location(id = 'url', refresh = False),
    html.Div(id = 'page-content')
])


@app.callback(Output('page-content', 'children'),
              Input('url', 'pathname'))
def display_page(pathname):
    if pathname == '/Cobertura_CV':
        return Resumen_Comunal()
    if pathname == '/Gestion_CV':
        return main_Table()
    else:
        return Homepage()


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

关键说明

  • 整个Dash应用只能有一个核心dash.Dash实例,所有组件和回调必须绑定到该实例上。
  • app.config.suppress_callback_exceptions = True的设置是正确的,它允许初始布局中不存在的组件对应的回调不报错,当页面切换后组件加载完成,回调即可正常触发。
  • 需确保所有组件ID在全局范围内唯一,避免不同页面的组件ID冲突导致回调异常。

内容的提问来源于stack exchange,提问作者Luis Briones Montecinos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:51:04