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

2024-09-30 16:36:39 发布

您现在位置:Python中文网/ 问答频道 /正文

当您在输入框中输入“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)

提前谢谢


Tags: marginimportdividappinputstylehtml
1条回答
网友
1楼 · 发布于 2024-09-30 16:36:39

无法通过访问布局(markerNameInp.value)中定义的Python对象来访问更新的组件值。这是因为每个访问Dash应用程序的用户与Dash应用程序的交互方式不同,并且状态存储在客户端(用户的浏览器)而不是服务器端(应用程序正在运行,Python对象markerNameInp所在的位置)

在您的用例中,可以使用dash.dependencies.State访问valuemarkerNameInp属性,该属性在组件更新时不会触发回调,但仍然可以捕获值

以下是更新的代码:

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)

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

相关问题 更多 >