【Dash】在回调的时候如何实现多个Output
程序员文章站
2022-07-14 17:13:46
...
参考自:Multiple-Outputs-in-Dash-Now-Available
Features(特性)
- Use a list/tuple of Output as output in callbacks.
- Return a tuple/list of value from the callbacks
- The returned list must have the same length as the list of output (返回和声明Output的个数应该相同)
- The output props are applied in the order they were declared in the output list(应该按照声明顺序返回)
代码:
import dash
import dash_core_components as dcc
import dash_table as dt
import dash_html_components as html
from dash.dependencies import Output, Input
from dash.exceptions import PreventUpdate
import plotly.graph_objs as go
sample_data = {
'series': {
'data': [
{'title': 'Game of Thrones', 'score': 9.5},
{'title': 'Stranger Things', 'score': 8.9},
{'title': 'Vikings', 'score': 8.6}
],
'style': {
'backgroundColor': '#ff998a'
}
},
'movies': {
'data': [
{'title': 'Rambo', 'score': 7.7},
{'title': 'The Terminator', 'score': 8.0},
{'title': 'Alien', 'score': 8.5}
],
'style': {
'backgroundColor': '#fff289'
}
}
}
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1('Multi output example'),
dcc.Dropdown(id='data-dropdown', options=[
{'label': 'Movies', 'value': 'movies'},
{'label': 'Series', 'value': 'series'}
], value='movies'),
html.Div([
dcc.Graph(id='graph'),
dt.DataTable(id='data-table', columns=[
{'name': 'Title', 'id': 'title'},
{'name': 'Score', 'id': 'score'}
])
])
], id='container')
#在此声明output
@app.callback([
Output('graph', 'figure'),
Output('data-table', 'data'),
Output('data-table', 'columns'),
Output('container', 'style')
], [Input('data-dropdown', 'value')])
def multi_output(value):
if value is None:
raise PreventUpdate
selected = sample_data[value]
data = selected['data']
columns = [
{'name': k.capitalize(), 'id': k}
for k in data[0].keys()
]
figure = go.Figure(
data=[
go.Bar(x=[x['score']], text=x['title'], name=x['title'])
for x in data
]
)
#在此返回output
return figure, data, columns, selected['style']
if __name__ == '__main__':
app.run_server(debug=True, port=8056)
效果:
更改了图、数据及其样式
在此之前,大家都是通过def 多个function来实现对多个Output的操作。
除此之外,官方文档里还有一个案例,但是我没怎么看懂,附上地址https://dash.plot.ly/state,最下面。
说是return dash.no_update, '{} is prime!'.format(num),dash.no_update
- # dash.no_update prevents any single output updating
- # (note: it's OK to use for a single-output callback too)