Exercise: Callback Functions
Practice with some lab exercises.
We'll cover the following...
Exercise 1
Create a simple Dash app that allows a user to select from a Dash Core Components radio button. The options should be "Cricket", "Swimming", "Running" and whichever option the user selects, output some text inside a paragraph HTML component returning the text You chose {sport_chosen}. Here sport_chosen is the parameter specified for the dash callback function. Set "Cricket" to the default if nothing has been actively selected by the user just yet.
Solution
-
A list of sports is created on line 2 and the first sport in the list (
Cricket) is set as the initially selected option. -
The app layout is set using the
dbc.Containermethod on line 9, which includes:-
Line 11: An
H1header element displaying “Exercise 1.” -
Line 14: A
RadioItemselement on allowing users to select a sport from the list withCricketpreselected. -
Line 20: A paragraph element (
P) with an ID ofoutput_textto display the selected sport later.
-
-
Line 25: A callback function is defined to update the
output_textparagraph element’s content when the user selects a different sport from the radio buttons. -
The callback function takes the selected sport and returns a formatted string displaying the chosen sport in lowercase.
Exercise 2
Create a simple Dash app that allows users to input a number using Dash Bootstrap Components and output the value when a sigmoid function has been applied to the given number. Display the content as a Dash markdown Component emulating the following presentation: ...