【问题标题】:How to use a button to trigger callback updates?如何使用按钮触发回调更新?
【发布时间】:2018-01-25 23:02:33
【问题描述】:

我刚刚开始使用 dash。以here 为例。我想转换下面的dash应用程序

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

在用户按下按钮时更新,而不是在输入字段的值更改时更新。我该如何做到这一点?

【问题讨论】:

  • 这原来是this问题的副本。

标签: python plotly-dash


【解决方案1】:

这是与post 类似的问题。在最新的dash_html_components 中有一个可用于按钮的单击事件,但它似乎还没有被完整记录。创建者 chriddyp 告诉 statedEvent 对象可能不会面向未来,但 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多