【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.Div html.Ul,你可以用它来动态添加或修改内部的 HTML 元素。
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 会自动更新图表的显示。
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 样式。你可以指定样式字典来改变组件的外观。
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 插件。
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.Input dcc.Dropdown
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
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.Tabs dcc.Accordion

8、'selectedData'

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

9、'src'

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

10、'data'

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

11、'columns'

  • 用于更新数据表组件的列配置,如 dash_table.DataTable

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Python Dash,可以使用回调装饰器来调用自身函数(self)。回调装饰器是一种装饰器模式,在Dash应用程序使用它可以简化代码,增加可读性和可维护性。 当我们需要在Dash应用程序使用回调函数时,可以使用`@app.callback`装饰器来定义回调函数,并将其与对应的输入和输出组件进行绑定。 首先,我们需要导入Dash库和回调装饰器: ``` import dash from dash.dependencies import Input, Output ``` 然后,创建Dash应用程序的实例: ``` app = dash.Dash(__name__) ``` 接下来,我们可以使用回调装饰器来定义回调函数。例如,我们定义一个简单的文本框和输出组件,当用户在文本框输入内容时,输出组件会实时更新为输入的内容: ``` @app.callback( Output('output', 'children'), [Input('input', 'value')] ) def update_output(value): return value ``` 在上述示例,`@app.callback`装饰器将`update_output`函数绑定到名为`output`的输出组件和名为`input`的输入组件上。`value`参数代表输入组件的值,`update_output`函数的返回值将作为输出组件的内容。 通过这种方式,我们可以在回调函数调用自身函数。例如,我们可以在`update_output`函数添加一些逻辑,根据输入的值进行判断并调用自身函数。 注意,为了防止无限递归调用,我们需要确保在适当的时候退出递归。可以使用条件语句或其他控制结构来实现这一点。 总而言之,Dash回调装饰器提供了一种方便的方式来定义和绑定回调函数。通过使用这些装饰器,我们可以在Dash应用程序调用自身函数,并实现更复杂的交互功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值