Dash中 基本的 callback 5

@app.callback

在Dash中,@app.callback 被用于创建交互性应用程序,它用于定义一个回调函数,该函数在应用程序中发生特定事件时被触发。回调函数可以修改应用程序的布局或更新图表等内容,从而实现动态交互。

下面是一个简单的 @app.callback 的基本结构:

python 复制代码
from dash import Dash, html, dcc, callback, Output, Input

app = Dash(__name__)

app.layout = html.Div([
    dcc.Input(id='input', type='text', value=''),
    html.Div(id='output')
])

@app.callback(
    Output('output', 'children'),
    [Input('input', 'value')]
)
def update_output(value):
    return f'You entered: {value}'

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

说明

复制代码
@app.callback 装饰器指定了回调函数 update_output,它将被触发当 Input 组件(dcc.Input)中的值发生变化时。
Output('output', 'children') 定义了回调函数的输出,它指示输出到 Output 组件(html.Div)的 'children' 属性。
[Input('input', 'value')] 则指定了回调函数的输入,表示回调函数接收来自 Input 组件 input 的 'value' 属性的输入。

在这个例子中,当用户在输入框中输入文本时,update_output 函数会被触发,将用户输入的文本显示在输出框中。

需要注意的是,回调函数中的参数名称必须与 @app.callback 装饰器中的 Input 和 Output 的组件和属性名称一致。

Input('input', 'value')\]即指 dcc.Input(id='input', type='text', value=''),输入内容,则value改变。 Output('output', 'children') 则是指将value写入到 html.Div(id='output') #### 美化上述例子的界面 可以使用Dash Bootstrap Components(dash_bootstrap_components)库提供的样式。这个库提供了一系列Bootstrap样式,可以让你的Dash应用看起来更现代和专业。 首先,确保已经安装了 dash-bootstrap-components:app = Dash(**name**, external_stylesheets=\[dbc.themes.BOOTSTRAP\])这是将样式引入页面。 ```python pip install dash-bootstrap-components ``` 代码: ```python from dash import Dash, html, dcc, callback, Output, Input import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dbc.Container( [ dbc.Row(dbc.Col(html.H1("交互式输入输出"), width=12)), dbc.Row( dbc.Col(dcc.Input(id='input', type='text', value='', placeholder='在这里输入文本'), width=12), className="mb-3", ), dbc.Row( dbc.Col(html.Div(id='output', className="mt-3"), width=12), className="mb-3", ), ], className="mt-5", ) @app.callback( Output('output', 'children'), [Input('input', 'value')] ) def update_output(value): return f'你输入的是: {value}' if __name__ == '__main__': app.run_server(debug=True) ``` ![在这里插入图片描述](https://file.jishuzhan.net/article/1739273400251060225/07926ae9f3cf8c6da9bc7ab20d59bbe1.webp)

相关推荐
gnawkhhkwang21 分钟前
Flask + YARA-Python*实现文件扫描功能
后端·python·flask
yj155830 分钟前
二手房翻新时怎样装修省钱?
python
max5006001 小时前
复现论文《A Fiber Bragg Grating Sensor System for Train Axle Counting》
开发语言·python·深度学习·机器学习·matlab·transformer·机器翻译
WSSWWWSSW1 小时前
Python高级编程与实践:Python网络编程基础与实践
开发语言·网络·python
mortimer1 小时前
Python GUI 应用启动优化实战:从3分钟到“秒开”的深度历程
python·github·pyqt
竹子_231 小时前
贪心算法解析
python·算法·贪心算法
三道杠卷胡2 小时前
【AI News | 20250804】每日AI进展
人工智能·python·语言模型·github·aigc
小沈熬夜秃头中୧⍤⃝2 小时前
Python 基础语法(二):流程控制语句详解
开发语言·数据库·python
max5006002 小时前
基于开源人脸识别模型实现情绪识别功能
python·深度学习·开源·transformer
黄晓魚3 小时前
open3d python 鞋底点云点胶路径识别
开发语言·python·open3d