本章介绍如何使用回调函数创建Dash应用程序:只要输入组件的属性发生更改,Dash就会自动调用Python函数。
1.一个简单的栗子
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
external_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.callback
decorator. 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.callback
decorator. 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
Input
items and then anyState
items are given in the same order as in the decorator.d. You must use the same
id
you gave a Dash component in theapp.layout
when referring to it as either an input or output of the@app.callback
decorator.e. The
@app.callback
decorator 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