python-3.x - 我不明白 python Dash @Callback 如何知道执行 def 函数

标签 python-3.x plotly-dash

我想了解@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() 组件(这可以是多个组件的列表,在这种情况下,使用 [] 将所有组件括起来.同样,InputState可以是列表,以表示可以影响或更改输出的多个输入或状态。

此外,如果我们看一下 Output('timeseries', 'figure'),我们告诉 dash 的是我们想要用 id 来 react 元素 code> 称为 timeseries,我们想要对此 id 的 figure 元素使用react。 figure 可以替换为 valuechildren,具体取决于我们想要更改的内容。类似的情况也适用于输入和状态。第一个参数描述元素的 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 元素,其 idtimeseries

关于python-3.x - 我不明白 python Dash @Callback 如何知道执行 def 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63048005/

相关文章:

python - 如何测试 popplerqt5 中的注释类型?

plotly-dash - 破折号 : Long-Running callback that streams tokens into a Markdown component

python - 如何在 dash/plotly 中使用 iframe? ( python /HTML)

python - 使用 python 3 将列表添加为树的子级

python-3.x - 使用 pandas from_dict 转换为数据帧时,不要使用字典中的键作为索引

python - 在 Python 中将包含 html 标签的字符串拆分为其构建 block

python - 带有自定义选项的 Dash 动态下拉菜单

python-3.x - Html 破折号表

python-3.x - Python Plotly-Dash 从 list 中删除 "inline",以便项目位于不同的行上

python - 在 Python 3.6 中导入库 "modin"时出错