Reset n_clicks property of a Button once it's pressed

Hi. How can I reset the n_clicks property of a Button once it’s pressed?
I’m defining my button in the layout as the following:

html.Button("random text", id="button_ID1", n_clicks=0)

Once the button is pressed, the n_clicks would increase to 1.
I’m using Input("button_ID1", "n_clicks") in my callbacks. But, then I want to reset the n_clicks to zero as if it’s an On-Off button.
Thanks in advance.

Hi @essi1990, just check whether n_clicks is odd or even:

    Output("some-component", "property"), 
    [Input("button_ID1", "n_clicks")]
def on_off(n):
    if not n or n % 2 == 0:
        #Action when OFF
        #Action when ON
1 Like

@RenaudLN Thanks for your prompt answer. This probably will result in strange behavior since it’s dependent on the actual number of clicks.
However, I like your implementation since it does not require outputting n_clicks property. I have to think more about the implementation though :thinking:

Another way I’m thinking is to use BooleanSwitch or PowerButton from Dash DAQ, and change their styles to be rectangular with some text just like the regular html.Button. I believe changing the style of PowerButton/BooleanSwitch is possible. I just need to research that.

Hi There,

I am encountering the same issue,
I wanted to ask if you found a solution.


Any updates here? This is very important for me to flush the n_clicks state while I retain all the other inputs entered by the user…

you can use dash.callback_context perhaps?

Output(“some-component”, “children”),
[Input(“button_ID1”, “n_clicks”)]
def on_button_press(n_clicks):

ctx = dash.callback_context
if not ctx.triggered:
    button_id = 'No clicks'
    button_id = ctx.triggered[0]['prop_id'].split('.')[0]

 if button_id=="button_ID1":
     return "button pressed"
     return ""
1 Like

Another option would be to create another component that stores the reset state (e.g. a Storage component), i.e. something like

@app.callback(Output("reset", "data"), [Input("reset_btn", "n_clicks")], [State("button_ID1", "n_clicks")])
def reset(_, n_clicks):
    return n_clicks

And then just substract this value in the other callback,

@app.callback(Output(“some-component”, “children”), [Input(“button_ID1”, "n_clicks")], [State("reset_btn", "n_clicks")])
def reset(n_clicks, reset):
    n_clicks -= reset
    # Do stuff here.
1 Like

This solution is work for me :

1 Like

Thank you.