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.
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:
if not n or n % 2 == 0:
#Action when OFF
#Action when ON
@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
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.
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?
ctx = dash.callback_context
if not ctx.triggered:
button_id = 'No clicks'
button_id = ctx.triggered['prop_id'].split('.')
return "button pressed"
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):
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.