提问人:Vijay B 提问时间:10/6/2021 更新时间:10/31/2021 访问量:2352
有没有办法将 Python 变量传递给 Plotly Dash clientside_callback?
Is there a way to pass Python variables to a Plotly Dash clientside_callback?
问:
我正在尝试在 Plotly Dash 中进行客户端回调,其中将执行 JavaScript 脚本。我在脚本的其他地方定义了一个 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 变量添加到我的客户端回调函数中?
答:
3赞
5eb
10/31/2021
#1
您可以直接将变量传递给布局中组件的属性。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()
评论