How to use a button to trigger callback updates?

只愿长相守 提交于 2019-12-11 03:50:03

问题


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:


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()


来源:https://stackoverflow.com/questions/45736656/how-to-use-a-button-to-trigger-callback-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!