13

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?

4

1 回答 1

12

这是与这篇文章类似的问题。在 latest 中有一个可用于按钮的点击事件dash_html_components,但它似乎还没有被完整记录。创造者 chriddyp 曾表示Event对象可能不会面向未来,但State应该如此。

使用State类似:

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

您可以将值用作输入,如果它们发生变化,则无需启动回调。回调仅在Input('button', 'n_clicks')更新时触发。

因此,对于您的示例,我添加了一个按钮并将 State 对象提供给您现有的 html.Input 的值:

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()
于 2017-08-17T22:56:31.633 回答