You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dash框架中如何动态修改html.Button组件的显示文本?

你之前修改title、data、value属性不生效,是因为html.Button的显示文本对应children属性,不属于你尝试修改的几个属性范畴。按以下方式调整即可实现点击按钮后替换按钮文本的需求:

调整核心逻辑

  • 给回调新增一个Output规则,指向按钮的children属性
  • 回调函数返回两组值,分别对应原有提示文本、按钮新文本
  • 增加初始加载状态判断,避免页面刚打开就修改按钮默认的Submit文本

完整可运行代码

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='输入内容后点击提交按钮')
])


@app.callback(
    # 新增按钮children的输出规则
    [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 '输入内容后点击提交按钮', 'Submit'
    # 优先使用输入框内容,输入为空时用默认提示
    new_button_text = value if value else '已提交'
    return (
        f'输入的内容为 "{value}",按钮已被点击 {n_clicks} 次',
        new_button_text
    )


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

运行后点击按钮,若输入框有内容,按钮文本会自动替换为输入框内容;如果输入框为空,按钮会默认显示「已提交」文本。

内容的提问来源于stack exchange,提问作者bbaxter256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:15:04