无法通过访问布局中定义的 Python 对象来访问更新的组件值(markerNameInp.value
)。这是因为访问 Dash 应用程序的每个用户都会以不同的方式与其进行交互,并且状态存储在客户端(用户的浏览器)而不是服务器端(应用程序运行的位置以及 Python 对象的位置)markerNameInp
位于)。
在您的用例中,可以访问value
的财产markerNameInp
通过使用dash.dependencies.State
,组件更新时不会触发回调,但仍然可以捕获值。
这是更新后的代码:
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
markerNameInp = dbc.Input(
id="markerNameInp",
placeholder="Enter name..",
style={
"min-width": "150px",
"width": "15%",
"margin-right": "20px",
"display": "inline-block",
"margin-bottom": "10px",
},
value="test",
)
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container(
children=[
html.Div([markerNameInp]),
dbc.Button("Enter", id="enter", color="primary", className="mr-1"),
html.Div(id="output"),
],
)
@app.callback(
Output("output", "children"),
[Input("enter", "n_clicks")],
[State("markerNameInp", "value")]
)
def func(n_clicks, marker_value):
return dbc.Label(marker_value)
if __name__ == "__main__":
app.run_server(debug=True)
(更改了引导代码以反映最佳实践,并为简单起见删除了一些样式)。