【问题标题】:Is there a way to pass Python variables to a Plotly Dash clientside_callback?有没有办法将 Python 变量传递给 Plotly Dash clientside_callback?
【发布时间】:2021-11-26 12:46:43
【问题描述】:

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

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 变量添加到我的客户端回调函数中?

【问题讨论】:

    标签: javascript python plotly plotly-dash client-side


    【解决方案1】:

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

    然后您可以将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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多