【Dash】Dash中@callback() 回调函数的Output() 参数

一、Dash 中的 @callback()

在Python中,@callback是一个用于注册回调函数的装饰器

Dash 的回调机制允许开发者创建交互式的Web应用,通过回调函数可以实现前端界面与后端逻辑的交互。

二、@callback() 的概念、定义和应用场景

概念

  • @callback 是 Dash 框架中的一个装饰器,用于将一个普通函数转变成一个回调函数,这个函数可以响应 Dash 应用中的用户交互。

定义

  • @callback 常与 Output 和 Input 类一起使用,定义了当输入组件的值发生变化时,哪个前端组件应该更新,以及如何更新。

应用场景

  • 需要根据用户输入、点击等交互更新前端显示的情况时使用。
  • 例如,当用户调整滑块时更新图表,或者在用户输入文本后显示结果。

三、@callback() 中 的常用类

  • Input():用于指定触发回调的组件和属性。例如:Input('component-id', 'property') 表示当指定组件的属性发生变化时,回调函数将被触发。
  • Output():用于指定回调函数的结果将更新到哪个组件的哪个属性。例如:Output('component-id', 'property') 表示回调函数的返回值将用来更新指定组件的属性。
  • State():用于在回调函数中提供额外的输入值,但它本身的变化不会触发回调。这个可以用于传递组件的当前状态,而不需要更新触发回调函数。

四、@callback() 中的 Output() 有哪些参数?

1、'children'

  • 用于更新组件的子元素。这通常用于容器组件,如html.Divhtml.Ul,你可以用它来动态添加或修改内部的HTML元素。
python 复制代码
import dash
from dash import html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Button('Add Test', id='add-text-button', n_clicks=0),
    html.Div(id='text-container')
])


@app.callback(
    Output('text-container', 'children'),
    [Input('add-text-button', 'n_clicks')]
)
def add_text(n_clicks):
    if n_clicks:
        return [html.P(f'This is text {i}') for i in range(n_clicks)]


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

2、'figure'

  • 用于更新图表组件 的内容,如dcc.Graph 。这个属性允许你传递图表的数据和配置,Dash会自动更新图表的显示。
python 复制代码
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px

app = dash.Dash(__name__)

# 定义应用布局
app.layout = html.Div([
    # 添加 dcc.Location 组件来捕获 URL 的路径
    dcc.Location(id='url', refresh=False),
    # 定义一个 Graph 组件来显示图表
    dcc.Graph(id='example-graph')
])


# 回调函数,根据 URL 路径更新图表
@app.callback(
    Output('example-graph', 'figure'),
    [Input('url', 'pathname')]
)
def update_graph(pathname):
    # 获取鸢尾花数据集
    df = px.data.iris()

    # 根据 pathname 来决定图表的数据和类型
    if pathname:
        # 假设 pathname 是 'sepal_length', 'sepal_widdth', 'petal_length', 'petal_width' 中的一个
        # 去除 pathname 前后的斜杠
        column_name = pathname.strip('/')
        if column_name in df.columns:
            fig = px.box(df, y=column_name)
            return fig
    # 如果 pathname 不匹配任何列,返回一个空的图表
    column_list = 'url可拼接:' + ','.join(df.columns)
    return {'data': [],
            'layout': {'title': f'No Data<br>{column_list}'}}        # 返回空图表


# 运行服务器
if __name__ == '__main__':
    app.run_server(debug=True)

3、'style'

  • 用于更新组件的 CSS 样式。你可以指定样式字典来改变组件的外观。
python 复制代码
import dash
from dash import html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Button('Change Style', id='change-style-button', n_clicks=0)


@app.callback(
    Output('change-style-button', 'style'),
    [Input('change-style-button', 'n_clicks')]
)
def change_style(n_clicks):
    if n_clicks % 2 == 1:
        return {'color': 'white', 'background-color': 'blue'}
    else:
        return {'color': 'black', 'background-color': 'lightgray'}


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

4、'className'

  • 用于更新组件的CSS 类名。这可以用于应用预定义的CSS 样式或 JavaScript插件。
python 复制代码
import dash
from dash import html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Button('Change Class', id='change-class-button', n_clicks=0),
    html.Div('Content', id='content-div'),
    html.Div(id='class-name-display')
])


@app.callback(
    Output('content-div', 'className'),
    [Input('change-class-button', 'n_clicks')]
)
def change_class(n_clicks):
    if n_clicks % 2 == 0:
        return 'new-class-a'
    else:
        return 'new-class-b'


@app.callback(
    Output('class-name-display', 'children'),
    [Input('content-div', 'className')]
)
def display_class_name(className):
    return f'The current class name is: {className}'


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

5、'value'

  • 用于更新输入组件 的值,如dcc.Inputdcc.Dropdown
python 复制代码
import dash
from dash import dcc, html
from dash.dependencies import Input, Output


app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    dcc.Input(id='input-field', value='Initial Value')
])


@app.callback(
    Output('input-field', 'value'),
    [Input('url', 'pathname')]
)
def update_input_value(pathname):
    return pathname if pathname else 'No Path Provided'


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

6、'options'

  • 用于更新下拉列表组件 的选项,如 dcc.Dropdown
python 复制代码
import dash
from dash import dcc, html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    dcc.Dropdown(id='my-dropdown')
])


@app.callback(
    Output('my-dropdown', 'options'),
    [Input('url', 'pathname')]
)
def update_dropdown_options(pathname):
    if pathname:
        options = [{'label': f'Option {i}', 'value': f'{i}'} for i in range(1,6)]
        return options


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

7、'active'

  • 用于更新选项卡或手风琴组件的当前活动项,如dcc.Tabsdcc.Accordion

8、'selectedData'

  • 用于更新图表组件 选中的数据点,如 dcc.Graph

9、'src'

  • 用于更新图片或视频组件的源,如 html.Imghtml.Video

10、'data'

  • 用于更新图表或数据表组件的数据,如 dcc.Graphdash_table.DataTable

11、'columns'

  • 用于更新数据表组件的列配置,如 dash_table.DataTable
相关推荐
superconvert9 小时前
主流流媒体的综合性能大 PK ( smart_rtmpd, srs, zlm, nginx rtmp )
websocket·ffmpeg·webrtc·hevc·rtmp·h264·hls·dash·rtsp·srt·flv
Book_熬夜!14 小时前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
字节跳动数据平台2 天前
火山引擎数智平台:高性能ChatBI的技术解读和落地实践
大数据·大模型·数据可视化·bi
William数据分析2 天前
[Python数据可视化] Plotly:交互式数据可视化的强大工具
python·数据分析·数据可视化
邢博士谈科教3 天前
比传统机器学习更先进的深度学习神经网络的二分类建模全流程教程
数据挖掘·r语言·数据可视化
GHUIJS3 天前
【Echarts】vue3打开echarts的正确方式
前端·vue.js·echarts·数据可视化
千汇数据的老司机4 天前
五星级可视化页面(25):非蓝色系,金色系可视化界面。
信息可视化·可视化·数据可视化
B站计算机毕业设计超人5 天前
计算机毕业设计Python知识图谱美团美食推荐系统 美团餐厅推荐系统 美团推荐系统 美食价格预测 美团爬虫 美食数据分析 美食可视化大屏
爬虫·python·深度学习·机器学习·数据分析·数据可视化·推荐算法