首页 > 解决方案 > 如何将变量存储在 dash 核心组件中

问题描述

我正在尝试使用 dash_core_components.Store 将变量存储到内存中,但它似乎没有将递增的数字保存到内存中。我想要发生的是每次按下按钮时,存储在内存中的数字都会增加 10 - 而变量似乎没有保存,只输出 15。

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

x = 5

app.layout = html.Div([
    dcc.Store(id='memory-data', data = {'the-data': x}),
    html.Div([
        html.Button('click me', id='add-button')
    ]),
    html.Div(id='debug-out'),
])

@app.callback(dash.dependencies.Output('debug-out', 'children'),
             [dash.dependencies.Input('add-button', 'n_clicks')],
             [dash.dependencies.State('memory-data', 'data')])
def button_pressed(clicks, data):
    
    data['the-data'] += 10
    return data['the-data']

标签: pythonplotly-dash

解决方案


您没有输出到dcc.Store组件,因此它永远不会改变。这就是它不断返回 15 的原因。您需要做的是设置两个回调,就像docs 中的这个示例一样。一个更新存储中的数据,另一个检索更新的数据。


推荐阅读