【问题标题】:Plotly Dash - Fire Callback only when switch state changesPlotly Dash - 仅在开关状态更改时触发回调
【发布时间】:2021-07-08 18:26:23
【问题描述】:

我在 Plotly Dash 中遇到以下问题: 我有一个布尔开关,我通过间隔方法每 10 秒更新一次它的状态,以检查它是否已被后台运行的第二个程序更改。 结构(简体)

    app.layout(
    html.div(id='switch')
    )

    @app.callback(Input('switch', 'on'),
                  Output("tracing_status","children"))
    def act_when_switch_state_changes():
       do_something()
    return output

    @app.callback(Input('interval-component', 'n_intervals'),
                  Output('switch','children'))
    def check switch_state():
        state = read_datebase()
        return html.div(daq.BooleanSwitch('id'='switch', on = state))

每次我在间隔组件中更新它的状态时,都会触发开关的回调。但是,我只希望它在其状态发生变化时触发。由于无状态设计,我在这里苦苦挣扎。

你有解决我的问题的方法吗?

谢谢! 所以 10 分钟后,回调计数器给我 60 的间隔分量和 59 的开关——即使我没有改变开关状态。

编辑: 或者,有没有办法通过 switch.on = True 等属性更改开关状态,而无需返回并重新加载整个 Div(switch) 元素?

【问题讨论】:

    标签: callback state plotly-dash


    【解决方案1】:

    是的,有一种方法可以更改开关,而无需每次都重新创建 daq.BooleanSwitch 元素,这是您应该采用的方式。相反,将开关包含在您的基本布局中并直接处理其状态。最小的例子:

    import random
    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output, State
    import dash_daq as daq
    
    app = dash.Dash(__name__)
    
    app.layout = html.Div([
        html.Div(id='text-output'),
        daq.BooleanSwitch(id='switch', on=True),
        dcc.Interval(id='interval-component', interval=1000),
    ])
    
    @app.callback(Output('text-output', 'children'),
                    Input('switch', 'on'))
    def act_when_switch_state_changes(switch):
        return 'switch is on' if switch else 'switch is off'
    
    @app.callback(Output('switch', 'on'),
                    Input('interval-component', 'n_intervals'),
                    State('switch', 'on'),
                    prevent_initial_call=True)
    def update_switch_state(n_intervals, old_state):
        new_state = random.choice([True, False]) # coin flip
        return dash.no_update if new_state == old_state else new_state
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    

    我用随机硬币翻转替换了您的read_database() 以获得新状态,但它当然可以是任何返回布尔值的东西。

    注意old_state 是如何在update_switch_state 中使用的,以确保开关的值仅在实际更改时才更新。这样做可以防止 ('switch', 'on') 作为 Input 的回调在开关未更改时触发。

    【讨论】:

    • 优秀的回答者!谢谢你告诉我,如何直接处理开关的状态:)
    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2020-12-07
    • 2020-03-17
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多