首页 > 解决方案 > 如何动态更改破折号中的 html.Button 文本?

问题描述

我尝试了不同的属性(标题、数据、值等),但它们没有成功。下面是直接取自 dash 文档的示例代码。我只是希望能够按下按钮并将按钮文本更改为“提交”之外的其他内容,最好是输入文本。

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div(dcc.Input(id='input-on-submit', type='text')),
    html.Button('Submit', id='submit-val', n_clicks=0),
    html.Div(id='container-button-basic',
             children='Enter a value and press submit')
])


@app.callback(
    Output('container-button-basic', 'children'),
    Input('submit-val', 'n_clicks'),
    dash.dependencies.State('input-on-submit', 'value')
)

def update_output(n_clicks, value):
    
    return ('The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    ))


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

标签: htmlbuttontextdynamicplotly-dash

解决方案


好吧,我发现我需要更新“children”属性。下面是执行我正在寻找的功能的代码:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div(dcc.Input(id='input-on-submit', type='text')),
    html.Button('Submit', id='submit-val', n_clicks=0),
    html.Div(id='container-button-basic',
             children='Enter a value and press submit')
])


@app.callback(
    Output('container-button-basic', 'children'),
    Output ('submit-val','children'),
    Input('submit-val', 'n_clicks'),
    dash.dependencies.State('input-on-submit', 'value')
)

def update_output(n_clicks, value):
    
    if n_clicks==0:
        return
    else:
        buttonText = value
    
    
    return ('The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    ), buttonText)


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

推荐阅读