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

DASH应用初始化登录页时出现KeyError: 'children'回调错误求助

问题根源

为啥会报KeyError: 'children'?因为你在display_page回调的else分支里,试图用字典索引的方式app.layout['children']访问组件子元素,但app.layout是html.Div组件实例,不是字典,根本不能这么访问属性。

两种修复方法

方法一:直接访问组件的children属性

修改display_page函数的else分支,把app.layout['children']换成app.layout.children[1].children。毕竟app.layout的children是个列表:第一个元素是dcc.Location,第二个才是带page-content ID的html.Div,我们要的是它里面的登录表单内容:

@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/success':
        return success_page_layout
    elif pathname == '/failure':
        return failure_page_layout
    else:
        # 获取page-content的初始登录表单内容
        return app.layout.children[1].children

方法二:单独抽离登录页布局(更推荐)

把初始登录页的布局单独做成一个变量,这样代码更清晰,也不用依赖app.layout的内部结构:

# 先定义登录页布局
login_page_layout = html.Div([
    html.H2('Login Page'),
    html.Div('Email'),
    dcc.Input(id='email', type='text', placeholder='Enter email'),
    html.Br(),
    html.Br(),
    html.Button('Login', id='login-button', n_clicks=0),
    html.Div(id='login-error')
], className='login-box')

app = dash.Dash(__name__)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    # 直接用预定义的登录布局
    html.Div(id='page-content', children=login_page_layout)
])

# 其他代码保持不变

@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/success':
        return success_page_layout
    elif pathname == '/failure':
        return failure_page_layout
    else:
        # 直接返回预定义的登录页
        return login_page_layout
额外提醒

第二种方法更值得用,因为它让布局模块化,以后改登录页内容时,不用动回调逻辑,代码更好维护。

内容的提问来源于stack exchange,提问作者Sana Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:05:27