Python Dash按钮点击无法触发绘图?回调函数问题求助
问题排查与修复
你的代码核心问题出在回调的输出目标设置错误,以及返回值类型不匹配,具体修正点如下:
1. 回调输出目标错误
原代码中回调的Output('main-plot', 'children')是错误的,dcc.Graph组件的核心可更新属性是figure,用来接收图表对象,而非children。
2. 返回值类型错误
不需要返回新的dcc.Graph组件,布局里已经存在id='main-plot'的dcc.Graph,直接返回生成的fig对象即可完成图表更新。
修复后的完整代码
import dash from dash import Dash, dcc, html, Input, Output import plotly.express as px import pandas as pd app = dash.Dash(__name__) app.layout = html.Div([ html.Br(), html.Button('start', id='btn-run', n_clicks=0, style={'width':'150px','height':'30px'}), dcc.Graph(id='main-plot', figure={}), html.Br() ]) @app.callback( Output('main-plot', 'figure'), # 修改为更新figure属性 Input('btn-run','n_clicks') ) def btn_run_click(btn_run): # 初始点击次数为0时返回空图表 if btn_run == 0 : return {} df = pd.DataFrame({ "Fruits":['Apples', 'Oranges', 'Bananas'], "Amount":[4,3,6] }) fig = px.bar(df, x = "Fruits", y = "Amount", barmode='group') return fig # 直接返回figure对象 if __name__ == '__main__': app.run_server(debug=False, port=8052)
额外优化建议
- 开发阶段可开启
debug=True,方便查看错误日志和实现代码热重载 - 初始状态若不想显示空图表,可返回带提示文本的空白布局,比如
px.scatter().update_layout(annotations=[dict(text="点击按钮生成图表", x=0.5, y=0.5, showarrow=False)])
内容的提问来源于stack exchange,提问作者nunun
相关产品推荐
相关产品推荐

