如何使用按钮触发回调更新?



我刚刚开始使用破折号。以这里为例。我想转换下面的破折号应用程序

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

在用户按下按钮时更新,而不是在输入字段的值更改时更新。我该如何实现此目的?

这是一个与这篇文章类似的问题。在最新的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')更新时,才会触发回调。

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

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

对于第一次加载,n_clicks可能是None

因此,您还可以检查是否希望在加载应用程序时不显示任何内容,而仅在单击按钮时显示结果。

if n_clicks is not None:
if n_clicks>0:
<your code>

最新更新