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

Dash回调报'Output'对象不可下标错误 多值输出问题求助

问题解答

1. Dash完全支持多值输出

你遇到的报错是代码语法错误和返回值匹配错误导致的,和多输出功能本身无关。

2. 代码存在的核心问题

问题1:回调装饰器语法错误

你在两个Output参数之间遗漏了逗号,Python会把后面的[Input('select_years', 'value')]识别为对前面Output对象的下标取值操作,这就是报错TypeError: 'Output' object is not subscriptable的直接原因。
原错误写法:

@app.callback(Output('text1', 'children'),
          Output('text2','children')
          [Input('select_years', 'value')],)

多输出场景建议将所有Output统一放在列表中,参数之间用逗号分隔,写法更规范不易出错。

问题2:返回值与输出数量不匹配

你定义了2个Output输出,对应需要返回2个值,每个值对应一个Output的children属性,但你原本返回的是包含4个元素的一个列表,完全不匹配输出规则。每个html.Div的children支持接收多个组件组成的列表,所以你需要把对应text1的组件打包为第一个返回值,对应text2的组件打包为第二个返回值。

额外可优化点

你原代码返回的内层组件重复定义了id='text1'、id='text2',和外层Div的id冲突,需要删除;同时两个标题都写了Current Year,不符合你要展示当年、上年销售额的需求,需要修正文本。

修正后的完整代码

html.Div([
        html.Div(id = 'text1'),
        html.Div(id = 'text2'),
    ],className='create_container2  three columns')

# 回调参数格式修正
@app.callback(
    [Output('text1', 'children'),
     Output('text2','children')],
    Input('select_years', 'value'),
)
def update_graph(select_years):
    sales8 = df.groupby(['Year'])['Sales'].sum().reset_index()
    current_year = sales8[(sales8['Year'] == select_years)]['Sales'].sum()
    sales9 = df.groupby('Year')['Sales'].sum().reset_index()
    sales9['PY'] = sales9['Sales'].shift(1)
    previous_year = sales9[(sales9['Year'] == select_years)]['PY'].sum()

    # 分别打包两个div的子组件
    text1_content = [
        html.H6(children='当年销售额',
                style={'textAlign': 'center',
                       'color': 'white'}),
        html.P('${0:,.2f}'.format(current_year),
               style={'textAlign': 'center',
                      'color': 'black',
                      'fontSize': 15,
                      'margin-top': '-10px'})
    ]
    text2_content = [
        html.H6(children='上年销售额',
                style={'textAlign': 'center',
                       'color': 'white'}),
        html.P('${0:,.2f}'.format(previous_year),
               style={'textAlign': 'center',
                      'color': 'black',
                      'fontSize': 15,
                      'margin-top': '-10px'})
    ]
    # 返回两个值对应两个Output
    return text1_content, text2_content

内容的提问来源于stack exchange,提问作者Muhammad hassaan haider

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:45:04