如何使用按钮触发回调更新? [英] How to use a button to trigger callback updates?

查看:121
本文介绍了如何使用按钮触发回调更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始破折号.以此处为例.我想转换下面的破折号应用程序

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?

推荐答案

这是与此

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.

像这样使用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')更新时,才会触发回调.

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

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

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

这篇关于如何使用按钮触发回调更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆