Dash Python:布局函数与@Callback结合

问题描述 投票:0回答:1

page1.py

import ... .layout as layout 

import dash

import pandas as pd

dash.register_page(__name__, path='/page_one') # I have an app.py which is running the app
       
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
                             'B': [6, 7, 8, 9, 10]})
df = df.reset_index()

layout = layout.update_page(df)

布局.py

import dash_bootstrap_components as dbc
from dash import dcc,html,Input, Output, callback
from dash import dash_table
import dash_daq as daq

def update_page(arg1):
    layout = html.Div(children = [
                    dbc.Col(daq.NumericInput(
                            id='my-numeric-input-1',
                            min=0,
                            max=100,
                            value=0,
                            label='Update Table',
                            labelPosition='top',
                            style={"paddingBottom": 15}),)

                   ,html.Br(),

                   dash_table.DataTable(
                       id='table',
                       data=arg1.to_dict('records'),
                       columns=[{"name": i, "id": i} for i in arg1.columns])

     ])

    return layout
@callback(
    Output('table', 'data'),
    Input('my-numeric-input-1', 'value'),
    )
def updateTable(x):
    if x>0:
        #ERROR here does not recognise the veriable arg1##

        arg1.iloc[1,1] = arg1.iloc[1,1]*x #I.e. do stuff to the table
        
    return arg1.to_dict('records')    
return arg1.to_dict('records') 

目标: 我有一个在 page1.py 中生成的简单数据框,我想将该 df 传递到在 layout.py 中创建的名为“update_page”的布局函数中(Note:我想创建多个页面,所以我想了想使用单个布局函数的代码效率更高)。使用数字输入框,我想使用回调更新 df,但是我收到一条错误,说它无法识别数据帧。有没有办法更新代码,以便 @callback 识别布局函数的参数并更新 df。

提前谢谢您。

python callback plotly plotly-dash
1个回答
0
投票

变量

arg1
被定义为函数
update_page
的参数,并且仅存在于该函数的范围内,它不存在于回调中。

您可以做的是使用

data
 获取表的 
State
并直接处理该对象(
State
允许您将额外的值传递给回调而不触发它)。

此外,您可能不想在数据保持不变时更新回调输出,这可以通过引发

PreventUpdate
异常来实现。

@callback(
    Output('table', 'data'),
    Input('my-numeric-input-1', 'value'),
    State('table', 'data'),
)
def updateTable(x, data):
    if x>0:
        # do stuff to `data`
        return data

    raise PreventUpdate
© www.soinside.com 2019 - 2024. All rights reserved.