Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
user25064 Avatar asked Aug 17 '17 13:08

user25064


1 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()
like image 135
Tyler Avatar answered Oct 04 '22 05:10

Tyler