Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dash Callback Function

Dash Callback Function

Dash allows developers to use Python to create dynamic, responsive user interfaces.

One of Dash's core features is the callback function (Callback), which enables the user interface to update in real time based on user input or actions.

The callback function is the core mechanism in Dash for handling user interaction. It allows you to dynamically update the application's layout or data when the user interacts with the application. Simply put, a callback is a Python function that is triggered when specific inputs change, and updates the output based on those input changes.

A typical Dash callback function consists of the following parts:

  1. Input: specifies which component's property changes will trigger the callback function.
  2. Output: specifies which component's properties will be updated after the callback function executes.
  3. State: optional parameter used to pass data that will not trigger the callback but is needed within it.
  4. Callback Function Body: contains the actual logic code used to process inputs and generate outputs.

Basic Structure of a Callback Function

@app.callback(

    Output(component_id='output-component', component_property='output-property'),

    Input(component_id='input-component', component_property='input-property')

)

def update_output(input_value):

    # Calculate output value based on input value

    return output_value

  1. Output:

  2. Specify the output target of the callback function.

  3. component_id: the ID of the target component.

  4. component_property: the property of the target component (such as children, value etc.).

  5. -

    Specify the output target of the callback function.

    -

    component_id: the ID of the target component.

    -

    component_property: the property of the target component (such as children, value etc.).

    1. Input:

    2. Specify the input source of the callback function.

    3. component_id: the ID of the input component.

    4. component_property: the property of the input component (such as value, n_clicks etc.).

    5. -

      Specify the input source of the callback function.

      -

      component_id: the ID of the input component.

      -

      component_property: the property of the input component (such as value, n_clicks etc.).

      1. Callback Function:

      2. Receives input values, computes, and returns output values.

      3. The function name can be customized (e.g. update_output).

      4. -

        Receives input values, computes, and returns output values.

        -

        The function name can be customized (e.g. update_output).

        Example

        The following example shows how to dynamically update text content based on the input box's value:

        Example

        from

        dash

        import

        Dash

        ,

        html

        ,

        dcc

        ,

        Input

        ,

        Output

        Create the Dash App

        app

        =

        Dash

        (

        name

        )

        Define the Layout

        app.

        layout

        =

        html.

        Div

        (

        [

            dcc.

        Input

        (

        id

        =

        'input'

        ,

        type

        =

        'text'

        ,

        placeholder

        =

        'Please enter something...'

        )

        ,

            html.

        Div

        (

        id

        =

        'output'

        )

        ]

        )

        Define the Callback Function

        @

        app.

        callback

        (

            Output

        (

        'output'

        ,

        'children'

        )

        ,

            Input

        (

        'input'

        ,

        'value'

        )

        )

        def

        update_output

        (

        input_value

        )

        :

           

        return

        f

        'You entered: {input_value}'

        Run the application

        if

        name

        ==

        'main'

        :

            app.

        run

        (

        debug

        =

        True

        )

        The following example shows how to dynamically update a chart based on the dropdown menu selection:

        Example

        from

        dash

        import

        Dash

        ,

        html

        ,

        dcc

        ,

        Input

        ,

        Output

        import

        plotly.

        express

        as

        px

        import

        pandas

        as

        pd

        Create the Dash App

        app

        =

        Dash

        (

        name

        )

        Sample data

        df

        =

        pd.

        DataFrame

        (

        {

           

        'City'

        :

        [

        'Beijing'

        ,

        'Shanghai'

        ,

        'Guangzhou'

        ,

        'Shenzhen'

        ]

        ,

           

        'Population'

        :

        [

        2171

        ,

        2424

        ,

        1490

        ,

        1303

        ]

        }

        )

        Define the Layout

        app.

        layout

        =

        html.

        Div

        (

        [

            dcc.

        Dropdown

        (

               

        id

        =

        'dropdown'

        ,

                options

        =

        [

        {

        'label'

        : city

        ,

        'value'

        : city

        }

        for

        city

        in

        df

        [

        'City'

        ]

        ]

        ,

                value

        =

        'Beijing'

         

        Default value

           

        )

        ,

            dcc.

        Graph

        (

        id

        =

        'graph'

        )

        ]

        )

        Define the Callback Function

        @

        app.

        callback

        (

            Output

        (

        'graph'

        ,

        'figure'

        )

        ,

            Input

        (

        'dropdown'

        ,

        'value'

        )

        )

        def

        update_graph

        (

        selected_city

        )

        :

            filtered_df

        =

        df

        [

        df

        [

        'City'

        ]

        ==

        selected_city

        ]

            fig

        =

        px.

        bar

        (

        filtered_df

        ,

        x

        =

        'City'

        ,

        y

        =

        'Population'

        ,

        title

        =

        f

        '{selected_city} Population Data'

        )

           

        return

        fig

        Run the application

        if

        name

        ==

        'main'

        :

            app.

        run

        (

        debug

        =

        True

        )

        After the above code runs, selecting a city in the dropdown menu will dynamically update the chart to display that city's population data.

        In the following example, after the user enters a number, the square of that number is displayed:

        Example

        from

        dash

        import

        Dash

        ,

        html

        ,

        dcc

        ,

        Input

        ,

        Output

        Create the Dash App

        app

        =

        Dash

        (

        name

        )

        Define the Layout

        app.

        layout

        =

        html.

        Div

        (

        [

            html.

        H1

        (

        "Calculate Square"

        )

        ,

         

        Title

            dcc.

        Input

        (

               

        id

        =

        'number-input'

        ,

         

        The input box's ID

               

        type

        =

        'number'

        ,

         

        The input box type is number

                placeholder

        =

        'Please enter a number...'

        ,

         

        The input box's placeholder text

                value

        =

        ''

         

        The initial value is empty

           

        )

        ,

            html.

        Div

        (

        id

        =

        'output'

        )

         

        The Div used to display the result

        ]

        )

        Define the Callback Function

        @

        app.

        callback

        (

            Output

        (

        'output'

        ,

        'children'

        )

        ,

         

        Output to the children property of the Div with id 'output'

            Input

        (

        'number-input'

        ,

        'value'

        )

         

        The input comes from the value property of the input box with id 'number-input'

        )

        def

        calculate_square

        (

        number

        )

        :

           

        if

        number

        is

        None

        or

        number

        ==

        ''

        :  

        If the input is empty

               

        return

        'Please enter a number.'

           

        try

        :

                number

        =

        float

        (

        number

        )

         

        Convert the input to a float

                square

        =

        number **

        2

         

        Calculate the square

               

        return

        f

        'The square of {number} is: {square}'

         

        Return result

           

        except

        ValueError

        :  

        If the input is not a number

               

        return

        'Please enter a valid number.'

        Run the application

        if

        name

        ==

        'main'

        :

            app.

        run

        (

        debug

        =

        True

        )

         

        Start the app; debug=True enables debug mode

        Code explanation:

        1. Layout Section:

        2. Callback Function:

        -

        Check whether the input is empty.

        -

        Convert the input to a float and calculate its square.

        -

        Return the formatted result.

        3. Run the App: When using app.run(debug=True) Start the app,debug=True indicates debug mode is enabled; the running effect is shown below:


        How a Callback Function Works

        1. Binding of Input and Output

        In Dash, the input and output of a callback function are specified through the Input and Output object.Input The object specifies which properties of which components changing will trigger the callback function, while the Output object specifies which properties of which components will be updated after the callback function executes.

        2. Triggering of the Callback Function

        When the user performs operations on the interface (such as entering text or clicking a button), the relevant component properties change. Dash detects these changes and automatically invokes the bound callback function.

        3. Execution of the Callback Function

        When the callback function executes, Dash passes the current value of the input property as a parameter to the callback function. The callback function computes or processes based on these input values and returns the new value of the output property. Dash automatically updates the returned value to the specified component property.


        Advanced Usage of Callback Functions

        1. Multiple Inputs and Outputs

        A callback function can have multiple inputs and outputs. For example:

        Example

        @

        app.

        callback

        (

           

        [

        Output

        (

        'output-div-1'

        ,

        'children'

        )

        ,

             Output

        (

        'output-div-2'

        ,

        'children'

        )

        ]

        ,

           

        [

        Input

        (

        'input-1'

        ,

        'value'

        )

        ,

             Input

        (

        'input-2'

        ,

        'value'

        )

        ]

        )

        def

        update_outputs

        (

        input1

        ,

        input2

        )

        :

           

        return

        f

        'Input 1: {input1}'

        ,

        f

        'Input 2: {input2}'

        In this example, the callback functionupdate_outputshas two inputs and two outputs. Wheninput-1orinput-2changes, the callback function is triggered and updates the two output components'childrenattribute.

        2. Using State

        Sometimes you may need to use data within a callback function that does not trigger the callback. In such cases, you can use theStateobject.Stateobject, which is similar to theInputobject, but it does not trigger the callback function.

        Example

        @

        app.

        callback

        (

            Output

        (

        'output-div'

        ,

        'children'

        )

        ,

           

        [

        Input

        (

        'submit-button'

        ,

        'n_clicks'

        )

        ]

        ,

           

        [

        State

        (

        'input-text'

        ,

        'value'

        )

        ]

        )

        def

        update_output

        (

        n_clicks

        ,

        input_value

        )

        :

           

        if

        n_clicks

        is

        None

        :

               

        return

        'No clicks yet'

           

        return

        f

        'Button clicked {n_clicks} times. Input: {input_value}'

        In this example,n_clicksis the input that triggers the callback, whileinput_valueis the state used in the callback function. The callback function is triggered only when the button is clicked, but it can use the current value of the input box.

        3. Preventing Redundant Callback Execution

        In some cases, a callback function may be triggered frequently, causing performance issues. To avoid this, you can usedash.no_updateto prevent unnecessary updates.

        Example

        @

        app.

        callback

        (

            Output

        (

        'output-div'

        ,

        'children'

        )

        ,

           

        [

        Input

        (

        'input-text'

        ,

        'value'

        )

        ]

        )

        def

        update_output

        (

        input_value

        )

        :

           

        if

        not

        input_value:

               

        return

        dash.

        no_update

           

        return

        f

        'You have entered: {input_value}'

        In this example, if the input box value is empty, the callback function will not update the output component.


        Common Problems and Solutions

        1. Callback Function Not Triggered

        If the callback function is not triggered as expected, it may be due to one of the following reasons:

        2. Callback Function Executes Slowly

        If the callback function executes slowly, consider the following optimization methods: