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

如何在Dash中使用daq.BooleanSwitch布尔开关回调更新图表

问题原因与解决方案

以下是你代码存在的问题和对应修正方法:

  • 缺少dash_core_components导入:你在布局里用了dcc.Graph组件,但代码开头没有导入对应的模块,会直接触发组件未定义的报错,需要先补充导入import dash_core_components as dcc
  • 布尔值判断逻辑冗余:daq.BooleanSwitch的on属性本身就是布尔类型,你不需要转成字符串再和"True"比对,直接判断if on:即可,避免字符串匹配出错
  • 回调未覆盖所有分支:当开关切换为关闭状态时,两个回调函数都没有返回值,图表回调会因为返回None触发更新异常,需要补充关闭状态的返回逻辑
  • 缺少合法的图表返回值:你注释掉了fig1的生成逻辑,开关开启时没有返回符合Plotly规范的图表对象,自然无法正常渲染图表
可运行的修正后代码
import dash
from dash.dependencies import Input, Output
import dash_daq as daq
import dash_html_components as html
import dash_core_components as dcc
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)

app.layout = html.Div([
    html.H1("Here we go"),
    daq.BooleanSwitch(id='my_pb', on=False, color="red"),
    html.Div(id='power-button-result-1'),
    dcc.Graph(id="plot")
])

@app.callback(
    Output('power-button-result-1', 'children'),
    Input('my_pb', 'on')
)
def update_output(on):
    if on:
        return "Hi I'm using DASH"
    return ""

@app.callback(
    Output('plot', 'figure'),
    Input('my_pb', 'on')
)
def figura(on):
    if on:
        # 示例绘图逻辑,可替换为你自己的业务代码
        df = pd.DataFrame({
            "类别": ["A", "B", "C", "D"],
            "数值": [10, 23, 15, 28]
        })
        fig1 = px.bar(df, x="类别", y="数值", title="开关开启后展示的图表")
        return fig1
    # 开关关闭时返回空图表
    return px.scatter(title="请开启开关查看图表")

if __name__ == "__main__":             
    app.run_server(port=1895)
运行效果

运行输出截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:36:07