我想了解@callback函数如何知道如何执行def update_graph,因为我没有看到任何使用变量的链接,例如在输入country_selector或回调中的值以及同时在def函数中所以回调知道我想要执行 def 函数。谁能给我简单的答案吗?
@app.callback(
Output('timeseries', 'figure'),
[Input('country_selector', 'value')]
)
def update_graph(selected_dropdown_value):
trace = []
for countriesAndTerritories in selected_dropdown_value:
#Erstelle Balkeindiagramm iterativ
trace.append(go.Bar(
x = df.month,
y= df[df["countriesAndTerritories"] == countriesAndTerritories] ["cases"],
name = countriesAndTerritories
))
data = trace
最佳答案
尝试解释回调。让我们看一下前几行:
@app.callback(
Output('timeseries', 'figure'),
[Input('country_selector', 'value')]
)
@app.callback
是 dash 对用户输入进行显示 react 的方式。它可以获取输入的输入
和输入的状态
并更改输出
。因此,定义了所有需要更改的 Output()
组件(这可以是多个组件的列表,在这种情况下,使用 []
将所有组件括起来.同样,Input
和State
可以是列表,以表示可以影响或更改输出的多个输入或状态。
此外,如果我们看一下 Output('timeseries', 'figure')
,我们告诉 dash 的是我们想要用 id 来 react 元素
code> 称为 timeseries
,我们想要对此 id 的 figure
元素使用react。 figure
可以替换为 value
或 children
,具体取决于我们想要更改的内容。类似的情况也适用于输入和状态。第一个参数描述元素的 id,第二个参数描述要更改的元素。
现在,转到 @app.callback
下面定义的 def
。该函数的名称本身并不是主要因素,但它的参数现在将是我们之前定义的所有输入。在此处的具体示例中,def update_graph(selected_dropdown_value):
,我们有一个输入 - 即 country_selector
的值。因此 selected_dropdown_value
现在将具有此值。
在这个函数内部,我们可以调用其他模块中或 dash 应用程序本身定义的其他业务逻辑函数,这些函数可能会接受这些输入
并生成或返回必要的输出。
示例伪代码:
def generate_bar(country):
#logic for extracting right info goes here
scatter_fig = go.Figure()
scatter_fig.add_trace(go.Bar(x=df['country'], y=df['counts']
scatter_fig.update_layout(title='new graph')
return scatter_fig
@app.callback(
Output('timeseries', 'figure'),
[Input('country_selector', 'value')]
)
def update_figs(selected_dropdown_value):
new_fig = generate_bar(selected_dropdown_value)
return new_fig
最后,这个 new_fig
现在替换了 figure
元素,其 id
为 timeseries
。
关于python-3.x - 我不明白 python Dash @Callback 如何知道执行 def 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63048005/