The world’s leading publication for data science, AI, and ML professionals.

Build Highly Interactive Projects with Jupyter Notebooks

Utilizing widgets to create user-friendly environments for constructing interactive Python and Data Science projects (Bonus- 2 Projects!)

Photo by Miguel Tomás on Unsplash
Photo by Miguel Tomás on Unsplash

Most Data Science and Python projects are often lines of code with little to no interactivity. For beginner programmers, this might be quite an issue as they need to constantly use print statements to understand the logic and workflow of the projects they are working on currently.

Even with the utility of Graphics User Interface (GUI) tools such as Tkinter, Kivy, and other similar libraries, the programming requirements are more. However, what if there was a way in which the users could utilize widgets and develop high interactivity with single lines of code within a Jupyter Notebook?

We will explore such scenarios in this article, where we will understand the basics of some of the interactive widget features. We will then also proceed to construct a couple of simple, fun, and interactive projects with these introductory widgets.

Before we dive straight into the concept of IPython widgets, it is essential to have a basic understanding of Jupyter Notebooks. In one of my previous articles, I have covered most of the fundamental concepts related to Jupyter Notebooks. You can check out this topic from the link provided below.

Everything You Need To Know About Jupyter Notebooks!

Note: GitHub link to the fundamentals and projects are provided at the end of the article.


Getting Started with IPython Widgets:

Ipywidgets, also known as Jupyter widgets or simply "widgets," are interactive HTML widgets for Jupyter notebooks and the IPython kernel. Widgets, in general, serve the purpose of creating an interactive GUI object for allowing its users to develop highly compact projects. They can also be used to synchronize stateful and stateless information between Python and JavaScript. For more information, please follow the link to these reference docs.

The procedure to install these widgets is quite convenient and can be done with the following command shown below. During the time of installation, the ipywidgets library automatically configures the Jupyter Notebook with all the necessary requirements without the need for any additional configurations.

pip install ipywidgets

Once we have successfully installed the ipywidgets library, we can proceed to create an interactive project in each Jupyter Notebook as desired. The first step before getting started with the utility of different types of widgets available in the library we need to import the ipywidgets library and the IPython display command for displaying these interactive widgets to the user.

# Importing the ipywidgets library and IPython display module
import ipywidgets as widgets
from IPython.display import display

Once the essential libraries are imported, the users can proceed to implement the numerous widgets available in the ipywidgets toolkit. In this section of the article, we will explore the fundamentals of some of the most commonly used widget options available to programmers and developers.

1. Slider:

widgets.IntSlider(value=50,
                  min=0,
                  max=100)
Image by Author
Image by Author

The first widget we will look at is the integer slider. It grants the users a useful option to use the slider within a specific range to cover a variety of operations for any particular task. However, you can only retrieve integer values with the integer slider, where we specify a default value and the minimum and maximum range of the slider.

The default orientation of the displayed slider is horizontal. The developers can make the orientation vertical as well. There are other options for sliders, including Float Sliders and Float Log Slider, among many other similar options.

2. Dropdown:

widgets.Dropdown(
    options=['1', '2', '3'],
    value='1',
    description='Number:',
    disabled=False,
)
Image by Author
Image by Author

The next interactive widget that we will look at in this section is the Dropdown widget. This widget displays a list of values which allows the user to choose from the available options. In the above code snippet, I have included the values for the dropdown box as 1, 2, and 3, with a default value of ‘1.’ The description provided is numbers. We can use the dropdown tool to perform actions for selecting any desired value for performing a specific task.

3. Textbox:

widgets.IntText(
    value=3,
    description='Numbers:',
    disabled=False
)
Image by Author
Image by Author

The next ipywidget we will look at is the textbox widget. As the name suggests, this widget is useful for inputting text data into a GUI box. In the above code snippet, we can notice that we have used the integer text widget allowing the user to input some integer type data. There are several other options for text box inputs that allow the user to input string data, including the Text and Text Area widget for performing the following action. Below is a sample code showing the alternative option for entering string-type data.

Alternative code:

widgets.Text(
    value='Hello World',
    placeholder='Type something',
    description='String:',
    disabled=False
)

4. Radio Button:

widgets.RadioButtons(
    options=['1', '2', '3'],
    description='Numbers:',
    disabled=False
)
Image by Author
Image by Author

The next ipywidget we will discuss is the radio button widget which allows the user to select a bunch of options. As shown in the above code snippet, we can provide a small description for the Radio Button and proceed to declare the options accordingly. There are a ton of experiments and projects that you can involve these radio buttons for, especially where you are allowed to select only a single option, such as multi-choice questions.

5. Checkbox:

widgets.Checkbox(
    value=False,
    description='I Agree to the terms and conditions',
    disabled=False,
    indent=False
)
Image by Author
Image by Author

The penultimate basic widget we will explore is the checkbox ipywidget. With the help of the checkbox widget, we can allow the user to pick a "yes" or "no" choice. The checkbox is initially unchecked. Once the user clicks on the checkbox, we can activate further commands and operations. These checkboxes are useful for a variety of projects, including the agreement of terms and conditions, as displayed above.

6. Toggle:

widgets.ToggleButtons(
    options=['1', '2', '3'],
    description='Numbers:',
    disabled=False,
    button_style=''
)
Image by Author
Image by Author

The final fundamental widget we will look at is the Toggle buttons. Using these widgets, we can toggle through a bunch of buttons where the roles and functionalities change accordingly for each button. In the above code snippet, we can notice that we have a list of options to display to the user as well as an additional description that we can add according to our requirements.

In the upcoming section, we will look at a couple of simple projects that we can construct with the help of ipywidgets in Jupyter Notebooks. Before we proceed, I would recommend the viewers who are interested in other similar GUI technologies to explore one of my previous articles, where I cover the seven best graphics tools to utilize for Python developers, with some starter codes from the link provided below.

7 Best UI Graphics Tools For Python Developers With Starter Codes

Note: In the widget icon on the menu bar of the Jupyter Notebook, we can click on the save widget option we temporarily save the widget state of the icon. If you are interested in learning more about the different types of widget options and the ipywidget library as a whole, I would recommend checking out the following documentation.


Project-1: Temperature Converter

With a basic understanding of the concept of Jupyter Notebook widgets, we will try to develop a couple of fun and simple interactive projects with these widgets. In the first project, we will focus on the conversion of temperature from Celsius to Fahrenheit. We will use the slider widget for this task. Let us get started with the project by importing the necessary libraries, as shown in the below code snippet.

# Importing the ipywidgets library and IPython display module
import ipywidgets as widgets
from IPython.display import display

In the next step, we will create the function for performing the temperature conversion process. We will define the temp function, which takes in the parameters as the value from the slider widget. The formula for converting the temperature from Celsius to Fahrenheit is mentioned below. You can also use 1.8 instead of the (9/5) fraction value used in the formula in the code snippet.

# Define the function for temperature conversion
def temp(slider_value):
    # Celsius to Fahrenheit conversion
    F = (slider_value *(9/5)) + 32
    return F

Once we finish defining our function for temperature conversion, we can proceed to define the slider widget through which we can control the Celsius numbers. We can store this widget in a variable, as shown below.

slider = widgets.IntSlider()

After defining the slider widget, we can proceed to display it so that the user can vary the values accordingly as they desire.

display(slider)
Image by Author
Image by Author

When the user moves the slider across the displayed scale, the slider value is updated accordingly, representing the Celsius scale. We can pass these values through the function we defined previously to obtain the required Fahrenheit output.

value = slider.value
temp(value)

Output:

77.0

When we pass the slider values as 25 degrees Celsius, we get the appropriate 77.0 degrees Fahrenheit response as anticipated. Such a build can also be utilized for other projects such as currency converters and so much more!


Project-2: Quiz

In our second project for this article, we will learn how to develop a simple interactive quiz project with the help of these ipywidgets. Let us get started by importing the essential library requirements as shown in the below code snippet.

# Importing the ipywidgets library and IPython display module
import ipywidgets as widgets
from IPython.display import display
import time

Once all the necessary libraries are imported, we can proceed to create the next two essential functions for this project. Firstly, we will define a function to check the answers to the relevant questions. This function takes in two argument parameters, namely the question numbers and the question answers input by the user. The answer is verified, and the user is notified if their answer is correct or incorrect.

In the next function, we will take in an input question number from the toggle button widget and display the questions with their respective multi-choice answers with the help of a radio button. We will return the value that is to be selected and output as the answer by the user (or player).

# Creating the function for storing the Questions and Answers for the mini-quiz
def answer_check(question, question_input):
    if question_input == "Question-1":
        if question.value == "7":
            print("Correct Answer!")

        else:
            print("Incorrect Answer!")

    elif question_input == "Question-2":
        if question.value == "366":
            print("Correct Answer!")

        else:
            print("Incorrect Answer!")
def mini_quiz(question):
    if question == 'Question-1':
#         q1 = widgets.IntText(value=0, description='How many continents are there in the world?')
        q = widgets.RadioButtons(options=['4', '5', '6', '7'], description='How many continents are there in the world?:')
        display(q)

    elif question == 'Question-2':
        q = widgets.RadioButtons(options=['364', '365', '366', '367'], description='How many days are there in a leap year?:')
        display(q)

    return q

In the next code block, we are giving the user an option to pick from the different types of questions they would like to view and answer. I have only given two toggle button options, but this project can be massively improved once you get a better hang of the ipywidgets library.

question = widgets.ToggleButtons(options=['Question-1', 'Question-2'], description='Quiz:')
display(question)
Image by Author
Image by Author

Let us now store the value of the toggle button as shown in the below code snippet.

question_input = question.value
question_input

Finally, we can start calling our functions to compute the questions and answers accordingly. Firstly, we will call the first function to pass and display the question with their respective answers.

question = mini_quiz(question_input)

Finally, we will call the function to check the appropriate answers. If the solution provided by the user is right, then a "Correct Answer!" comment is displayed. Otherwise, an Incorrect Answer!" comment is displayed.

answer_check(question, question_input)
Image by Author
Image by Author

The screenshot above shows what happens when the user selects an incorrect option.

Image by Author
Image by Author

The screenshot above represents what happens when the user selects the right option. There are several additional improvements and different varieties of projects that you can construct with this library. I would highly encourage the viewers to try out numerous different types of projects.


Conclusion:

Photo by The Average Tech Guy on Unsplash
Photo by The Average Tech Guy on Unsplash

"In some ways, programming is like painting. You start with a blank canvas and certain basic raw materials. You use a combination of science, art, and craft to determine what to do with them." — Andrew Hunt

Interactivity plays a humungous role in developing a user-friendly environment as well as enabling beginner Data Science and Programming enthusiasts to explore numerous concepts with a better intuitive understanding. Adding a variety of additional widgets and interactive features helps in making navigation and exploring of projects simpler, as you are able to control multiple parameters with ease.

In this article, we explored the ipywidgets library and the numerous features that it grants access to its users. We firstly understood some of the brilliant basic widgets that we can utilize within the Jupyter Notebooks. We then constructed a couple of simple, fun, and interactive Python projects that you can easily build with the help of this tool.

If you want to get notified about my articles as soon as they go up, check out the following link to subscribe for email recommendations. If you wish to support other authors and me, then subscribe to the below link.

Join Medium with my referral link – Bharath K

If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible. You can access the fundamentals and projects from the following GitHub link.

Check out some of my other articles in relation to the topic covered in this piece that you might also enjoy reading!

Best Seaborn Visualizations for Data Science

7 Python Programming Tips To Improve Your Productivity

Develop Your Weather Application with Python in Less Than 10 Lines

Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!


Related Articles