Python Plotly Dash - 如何在不使用回调的情况下访问更新的组件值?

2024-02-05

当您在输入框中输入“test”以外的内容并按 Enter 键时,标签应更改以反映该输入。

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


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()

app.layout = html.Div(style={'font':'Frutiger Linotype, sans-serif',
                             'margin-left':'50px','margin-right':'50px'},
    children=[
        html.Div([markerNameInp]),
        dbc.Button('Enter',id='enter',
                            color = 'primary',
                            className='mr-1',
                            style={'height':'40px'}),
        html.Div(id="output")
        ])

@app.callback(
    Output(component_id='output', component_property='children'),
    [Input(component_id='enter', component_property='n_clicks')]
)

def func(enter_clicks):
    return dbc.Label(markerNameInp.value)

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

提前致谢。


无法通过访问布局中定义的 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)

(更改了引导代码以反映最佳实践,并为简单起见删除了一些样式)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python Plotly Dash - 如何在不使用回调的情况下访问更新的组件值? 的相关文章

随机推荐