本章介绍如何使用回调函数创建Dash应用程序:只要输入组件的属性发生更改,Dash就会自动调用Python函数。

1.一个简单的栗子

  1. import dash
  2. import dash_core_components as dcc
  3. import dash_html_components as html
  4. from dash.dependencies import Input, Output
  5. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
  6. app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
  7. app.layout = html.Div([
  8. html.H6("Change the value in the text box to see callbacks in action!"),
  9. html.Div(["Input: ",
  10. dcc.Input(id='my-input', value='initial value', type='text')]),
  11. html.Br(),
  12. html.Div(id='my-output'),
  13. ])
  14. @app.callback(
  15. Output(component_id='my-output', component_property='children'),
  16. Input(component_id='my-input', component_property='value')
  17. )
  18. def update_output_div(input_value):
  19. return 'Output: {}'.format(input_value)
  20. if __name__ == '__main__':
  21. app.run_server(debug=True)

image.png

详细拆解一下这个例子:

  1. InputOutput用被声明的方式去装饰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 any State items are given in the same order as in the decorator.

d. You must use the same id you gave a Dash component in the app.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 通过inputoutput的数组进行参数控制。inputoutput的参数一致,都是以HTMLid来进行定位元素,再output