如何在 Python-Plotly-Dash 布局中使用回调中的变量?

问题描述

我想用动态数量的组件(特别是 NumericInputs)绘制我的 Dash 布局。当这个数字是静态的时,一切都很好,我可以通过回调和一切来改变这些值。我使用 for 来控制它。

但是,当我想更改组件数量时(从最大数量开始,小于该数量时进行调整),它附加到初始尺寸和标签。我想使用 dcc.Store(id='k') 等回调中的会话变量来控制它,但没有。我找到了在其他回调中使用它们的解决方案,实际上我在它们之间使用它们,但这次我需要在布局上下文中使用它。

对此有什么想法或经验吗?谢谢!

rows = [html.Tr([html.Td(categories[i]['name'],id={'type': 'categories_name','index': i}),html.Td(categories[i]['size'],id={'type': 'categories_size',html.Td(daq.NumericInput(id={'type': 'threshold','index': i},min=0,max=categories[i]['size'],value=categories[i]['size'],size=80)),html.Td("0%",id={'type': 'percent','index': i})])

for i in range(k) if  i<(dcc.Store(id='k'))]

containment_body = [html.Tbody(rows)]
containment_table = dbc.Table(table_header + containment_body,bordered=False,className="text-right table-borderless table-sm m-0")

enter image description here

解决方法

我尝试了很多方法来解决,最后使用了多页应用程序。我还使用了从回调和 Flask cookie 调用的 get_layout 方法。见https://dash.plotly.com/urls。它保留了响应式功能。

 @dash_app.callback(
   Output('page-content','children'),[Input('url','pathname')])
def display_page(pathname):
    print ("Displaying",pathname)
    if pathname == '/':
        dash.callback_context.response.set_cookie('campus_cookie',"/campus1")
        return get_layout(len(campuses["campus1"]["categories"]),campuses["campus1"]["no_solutions"],campuses["campus1"]["budget"],campuses["campus1"]["buckets"],campuses["campus1"]["d"],campuses["campus1"]["pi"],campuses["campus1"]["p"],campuses["campus1"]["categories"])
    else:
        dash.callback_context.response.set_cookie('campus_cookie',pathname)            
        return get_layout(len(campuses[pathname[1:]]["categories"]),campuses[pathname[1:]]["no_solutions"],campuses[pathname[1:]]["budget"],campuses[pathname[1:]]["buckets"],campuses[pathname[1:]]["d"],campuses[pathname[1:]]["pi"],campuses[pathname[1:]]["p"],campuses[pathname[1:]]["categories"])