How to use a button to trigger callback updates?

I am just getting started with dash. Taking the example from here. I want to convert the dash app below

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Div(id='my-div')
])
@app.callback( Output(component_id='my-div', component_property='children'), [Input(component_id='my-id', component_property='value')]
)
def update_output_div(input_value): return 'You\'ve entered "{}"'.format(input_value)
if __name__ == '__main__': app.run_server()

To update when the user presses a button not when the value of the input field changes. How do I accomplish this?

1

2 Answers

This is a similar question to this post. There is a click event available for a button in the latest dash_html_components, but it doesn't appear to be fully documented yet. The creator, chriddyp, has stated that the Event object may not be future-proof, but that State should be.

Using State like:

@app.callback( Output('output', 'children'), [Input('button-2', 'n_clicks')], state=[State('input-1', 'value'), State('input-2', 'value'), State('slider-1', 'value')])

you can use values as inputs, without initiating the callback if they change. The callback only fires if the Input('button', 'n_clicks') updates.

So for your example, I've added a button and fed the State object your existing html.Input's value:

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Button('Click Me', id='button'), html.Div(id='my-div')
])
@app.callback( Output(component_id='my-div', component_property='children'), [Input('button', 'n_clicks')], state=[State(component_id='my-id', component_property='value')]
)
def update_output_div(n_clicks, input_value): return 'You\'ve entered "{}" and clicked {} times'.format(input_value, n_clicks)
if __name__ == '__main__': app.run_server()

For the first-time load, n_clicks might be None.

So, you can also have a check if you want nothing to show up when you load the app but only show up the result when the button is clicked.

if n_clicks is not None: if n_clicks>0: <your code>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like