本章介绍如何使用回调函数创建Dash应用程序:只要输入组件的属性发生更改,Dash就会自动调用Python函数。
1.一个简单的栗子
import dashimport dash_core_components as dccimport dash_html_components as htmlfrom dash.dependencies import Input, Outputexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.layout = html.Div([html.H6("Change the value in the text box to see callbacks in action!"),html.Div(["Input: ",dcc.Input(id='my-input', value='initial value', type='text')]),html.Br(),html.Div(id='my-output'),])@app.callback(Output(component_id='my-output', component_property='children'),Input(component_id='my-input', component_property='value'))def update_output_div(input_value):return 'Output: {}'.format(input_value)if __name__ == '__main__':app.run_server(debug=True)
详细拆解一下这个例子:
Input和Output用被声明的方式去装饰app.callback。Learn more about using the
@app.callbackdecorator. a. By writing this decorator, we’re telling Dash to call this function for us whenever the value of the “input” component (the text box) changes in order to update the children of the “output” component on the page (the HTML div).
b. You can use any name for the function that is wrapped by the
@app.callbackdecorator. The convention is that the name describes the callback output(s).c. You can use any name for the function arguments, but you must use the same names inside the callback function as you do in its definition, just like in a regular Python function. The arguments are positional: first the
Inputitems and then anyStateitems are given in the same order as in the decorator.d. You must use the same
idyou gave a Dash component in theapp.layoutwhen referring to it as either an input or output of the@app.callbackdecorator.e. The
@app.callbackdecorator needs to be directly above the callback function declaration. If there is a blank line between the decorator and the function definition, the callback registration will not be successful.f. If you’re curious about what the decorator syntax means under the hood, you can read this StackOverflow answer and learn more about decorators by reading PEP 318 — Decorators for Functions and Methods. @callback 通过
input和output的数组进行参数控制。input和output的参数一致,都是以HTML的id来进行定位元素,再output

