Plotly Dash回调函数问题:实现年份下拉框按需启用
修复Plotly Dash中控制年份下拉框可用性的回调问题
你的代码存在两个关键错误,导致回调函数无法正常工作,以下是具体修正方案:
问题分析
- 参数命名非法:Python函数参数不允许使用连字符,
dropdown-statistics这种写法会触发语法错误,需改为下划线命名dropdown_statistics - 条件判断逻辑错误:你在if语句里把字符串
'dropdown-statistics'和目标值比较,这永远不会成立,应该使用传入的参数变量进行判断
修正后的完整代码
import dash from dash import html, dcc from dash.dependencies import Input, Output app = dash.Dash(__name__) # 补充年份列表定义(原代码未给出,需确保实际运行时已正确定义) year_list = list(range(1980, 2014)) app.layout = html.Div( children=[ html.H1('Automobile Statistics Dashboard 1980 - 2013', style={'textAlign': 'center', 'color': '#503D36','font-size': 24}), html.Div([html.Label('Select Statistics'), dcc.Dropdown(id='dropdown-statistics', options=[{'label': 'Yearly Statistics', 'value': 'Yearly Statistics'}, {'label': 'Recession Period Statistics', 'value': 'Recession Period Statistics'}], placeholder='Select a Report', style= {'width': '80%', 'padding': '3px', 'font-size': 20, 'text-Align': 'center'})]), html.Div([html.Label('Select Year'), dcc.Dropdown(id='select-year', options=[{'label': i, 'value': i} for i in year_list], placeholder='1980', style= {'width': '80%', 'padding': '3px', 'font-size': 20, 'text-Align': 'center'}, disabled=True # 默认禁用,匹配初始未选择报表的状态 )]), html.Div(id='output-container', className='chart-grid', style= {'display': 'flex'}), ] ) # 修正后的回调函数 @app.callback( Output(component_id='select-year', component_property='disabled'), Input(component_id='dropdown-statistics',component_property='value')) def update_input_container(dropdown_statistics): # 仅当选中Yearly Statistics时启用年份下拉框 if dropdown_statistics == 'Yearly Statistics': return False # 其他情况(未选择/选中Recession Period Statistics)均禁用 return True # Run the Dash app if __name__ == '__main__': app.run_server(debug=True)
额外说明
- 补充了
year_list的定义示例,实际运行时可根据数据源调整范围 - 默认将年份下拉框设为
disabled=True,符合用户未选择报表类型时的预期状态 - 简化了回调逻辑:只需判断选中值是否为
Yearly Statistics,其余情况统一禁用
内容的提问来源于stack exchange,提问作者Frank Vega
相关产品推荐
相关产品推荐

