如何在不使用回调的情况下访问更新的组件值? [英] Python Plotly Dash - How do I access updated component value without using callback?

查看:15
本文介绍了如何在不使用回调的情况下访问更新的组件值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在输入框中输入测试之外的内容并按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)

提前谢谢。

推荐答案

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

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

以下是更新后的代码:

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)

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

这篇关于如何在不使用回调的情况下访问更新的组件值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆