# HIDDEN
# Clear previously defined variables
%reset -f
A Simple Webpage¶
In this section, you will create and publish a simple interactive webpage!
In Jupyter, create a notebook and name it tutorial.ipynb
. Type or paste in the code from this tutorial into the notebook.
Using Interact¶
The ipywidgets
library provides the simplest way to get started writing interactive documents. Although the library itself has its own documentation, we will provide a quick overview to let you get started as quickly as possible.
We start by importing the interact
function:
from ipywidgets import interact
The interact
function takes in a function and produces an interface to call the function with different parameters.
def square(x):
return x * x
Pass the square
function into interact
and specify square
's arguments as keyword arguments:
interact(square, x=10);
To control the range of values x
can take, you can pass in a tuple of the same format as Python's range
function:
interact(square, x=(0, 100, 10));
Notice how dragging the slider changes the input to the square
function and automatically updates the output. This is a powerful idea that we will build on for the rest of this tutorial.
By using interact
, you can build complex widget-based interfaces in a notebook. These widgets will appear in your resulting webpage, giving your page interactivity.
Widget Types¶
Notice that interact
automatically generates a slider because the argument is numeric. Other types of arguments will generate different types of interfaces. For example, a string will generate a textbox.
def friends(name, number):
return '{} has {} friends!'.format(name, number)
interact(friends, name='Sam', number=(5, 10));
And a dictionary will generate a dropdown menu:
interact(friends, name='Sam', number={'One': 1, 'Five': 5, 'Ten': 10});
Here's the complete list of each argument type and the widget it generates:
Keyword argument | Widget |
---|---|
True or False |
Checkbox |
'Hi there' |
Text |
value or (min,max) or (min,max,step) if integers are passed | IntSlider |
value or (min,max) or (min,max,step) if floats are passed | FloatSlider |
['orange','apple'] or {'one':1,'two':2} |
Dropdown |
You may also use the widget classes in ipywidgets
in the calls to interact
to have more fine-grained control over the interface. For more details on using interact
, see the official ipywidgets
documentation.
You are now ready to publish your webpage! Proceed to the next page of the tutorial.