首页 > 解决方案 > 有没有办法将 Python 变量传递给 Plotly Dash clientside_callback?

问题描述

我正在尝试在将执行 JavaScript 脚本的 Plotly Dash 中进行客户端回调。我在脚本的其他地方定义了一个 Python 变量,现在我想将该变量传递给我有我的脚本的客户端回调。这是代码片段:

python_variable = 'string or some variable'

app.clientside_callback(
    """
    function(n_clicks, user_input) {
        if (n_clicks){
            alert(%{user_input} + %{python_variable});
        }
    }
    """,
    Output('dummy_div', 'children'),
    [Input('btn', 'n_clicks'),
     Input('user_input', value)]

我不知道如何将我的 python_variable 放在 dcc.Store 中,因为我在页面加载期间加载变量(对此没有回调)。是否可以将我的 Python 变量添加到我的客户端回调函数中?

标签: javascriptpythonplotlyplotly-dashclient-side

解决方案


您可以直接将变量传递给布局data中组件的属性。dcc.Store

然后,您可以将Store组件的data属性作为State.

MWE:

from dash import Dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html

python_variable = "string or some variable"

app = Dash(__name__)

app.layout = html.Div(
    [
        dcc.Input(id="input", value="", type="text"),
        html.Div(id="output"),
        dcc.Store(id="store", data=python_variable),
    ]
)

app.clientside_callback(
    """
    function(input, python_variable) {
        return `${python_variable}: ${input}`
    }
    """,
    Output("output", "children"),
    Input("input", "value"),
    State("store", "data"),
)

if __name__ == "__main__":
    app.run_server()

推荐阅读