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

2024-02-16

我刚刚开始使用破折号。举个例子here https://plot.ly/dash/getting-started-part-2#interactivity。我想转换下面的破折号应用程序

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

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


这是一个与此类似的问题post https://stackoverflow.com/questions/45579844/dash-core-component-for-basic-button-with-click-event。最新的按钮有一个点击事件dash_html_components,但似乎尚未完整记录。创作者 Chriddyp 拥有stated https://community.plot.ly/t/is-there-a-way-to-only-update-on-a-button-press-for-apps-where-updates-are-slow/4679/7认为Event对象可能不是面向未来的,但是State应该。

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')])

您可以使用值作为输入,而无需在它们更改时启动回调。仅当以下情况时才会触发回调Input('button', 'n_clicks')更新。

因此,对于您的示例,我添加了一个按钮并将现有 html.Input 的值提供给 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用按钮触发回调更新? 的相关文章