Hosted by CoCalc
Download
Kernel: Python 3 (SageMath)

Widget List

import ipywidgets as widgets

Numeric widgets

There are many widgets distributed with ipywidgets that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing Float with Int in the widget name, you can find the Integer equivalent.

IntSlider

  • The slider is displayed with a specified, initial value. Lower and upper bounds are defined by min and max, and the value can be incremented according to the step parameter.

  • The slider's label is defined by description parameter

  • The slider's orientation is either 'horizontal' (default) or 'vertical'

  • readout displays the current value of the slider next to it. The options are True (default) or False

    • readout_format specifies the format function used to represent slider value. The default is '.2f'

from pylab import * plot(np.sin(np.linspace(0, 20, 100)));
Image in a Jupyter notebook
plt
<module 'matplotlib.pyplot' from '/ext/sage/9.6/local/var/lib/sage/venv-python3.10.3/lib/python3.10/site-packages/matplotlib/pyplot.py'>
widgets.IntSlider( value=7, min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' )
IntSlider(value=7, continuous_update=False, description='Test:', max=10)

FloatSlider

widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', )
FloatSlider(value=7.5, continuous_update=False, description='Test:', max=10.0, readout_format='.1f')

An example of sliders displayed vertically.

widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.1f', )
FloatSlider(value=7.5, continuous_update=False, description='Test:', max=10.0, orientation='vertical', readout…

FloatLogSlider

The FloatLogSlider has a log scale, which makes it easy to have a slider that covers a wide range of positive magnitudes. The min and max refer to the minimum and maximum exponents of the base, and the value refers to the actual value of the slider.

widgets.FloatLogSlider( value=10, base=10, min=-10, # max exponent of base max=10, # min exponent of base step=0.2, # exponent step description='Log Slider' )
FloatLogSlider(value=10.0, description='Log Slider', max=10.0, min=-10.0, step=0.2)

IntRangeSlider

widgets.IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', )
IntRangeSlider(value=(5, 7), continuous_update=False, description='Test:', max=10)

FloatRangeSlider

widgets.FloatRangeSlider( value=[5, 7.5], min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', )
FloatRangeSlider(value=(5.0, 7.5), continuous_update=False, description='Test:', max=10.0, readout_format='.1f…

IntProgress

widgets.IntProgress( value=7, min=0, max=10, description='Loading:', bar_style='', # 'success', 'info', 'warning', 'danger' or '' style={'bar_color': 'maroon'}, orientation='horizontal' )
IntProgress(value=7, description='Loading:', max=10, style=ProgressStyle(bar_color='maroon'))

FloatProgress

widgets.FloatProgress( value=7.5, min=0, max=10.0, description='Loading:', bar_style='info', style={'bar_color': '#ffff00'}, orientation='horizontal' )
FloatProgress(value=7.5, bar_style='info', description='Loading:', max=10.0, style=ProgressStyle(bar_color='#f…

The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter.

BoundedIntText

widgets.BoundedIntText( value=7, min=0, max=10, step=1, description='Text:', disabled=False )
BoundedIntText(value=7, description='Text:', max=10)

BoundedFloatText

widgets.BoundedFloatText( value=7.5, min=0, max=10.0, step=0.1, description='Text:', disabled=False )
BoundedFloatText(value=7.5, description='Text:', max=10.0, step=0.1)

IntText

widgets.IntText( value=7, description='Any:', disabled=False )
IntText(value=7, description='Any:')

FloatText

widgets.FloatText( value=7.5, description='Any:', disabled=False )
FloatText(value=7.5, description='Any:')

Boolean widgets

There are three widgets that are designed to display a boolean value.

ToggleButton

widgets.ToggleButton( value=False, description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='check' # (FontAwesome names without the `fa-` prefix) )
ToggleButton(value=False, description='Click me', icon='check', tooltip='Description')

Checkbox

  • value specifies the value of the checkbox

  • indent parameter places an indented checkbox, aligned with other controls. Options are True (default) or False

widgets.Checkbox( value=False, description='Check me', disabled=False, indent=False )
Checkbox(value=False, description='Check me', indent=False)

Valid

The valid widget provides a read-only indicator.

widgets.Valid( value=False, description='Valid!', )
Valid(value=False, description='Valid!')

Selection widgets

There are several widgets that can be used to display single selection lists, and two that can be used to select multiple values. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list (options are either (label, value) pairs, or simply values for which the labels are derived by calling str).

Changes in *ipywidgets 8*:

Selection widgets no longer accept a dictionary of options. Pass a list of key-value pairs instead.

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

The following is also valid, displaying the words 'One', 'Two', 'Three' as the dropdown choices but returning the values 1, 2, 3.

widgets.Dropdown( options=[('One', 1), ('Two', 2), ('Three', 3)], value=2, description='Number:', )
Dropdown(description='Number:', index=1, options=(('One', 1), ('Two', 2), ('Three', 3)), value=2)

RadioButtons

widgets.RadioButtons( options=['pepperoni', 'pineapple', 'anchovies'], # value='pineapple', # Defaults to 'pineapple' # layout={'width': 'max-content'}, # If the items' names are long description='Pizza topping:', disabled=False )
RadioButtons(description='Pizza topping:', options=('pepperoni', 'pineapple', 'anchovies'), value='pepperoni')

With dynamic layout and very long labels

widgets.Box( [ widgets.Label(value='Pizza topping with a very long label:'), widgets.RadioButtons( options=[ 'pepperoni', 'pineapple', 'anchovies', 'and the long name that will fit fine and the long name that will fit fine and the long name that will fit fine ' ], layout={'width': 'max-content'} ) ] )
Box(children=(Label(value='Pizza topping with a very long label:'), RadioButtons(layout=Layout(width='max-cont…

Select

widgets.Select( options=['Linux', 'Windows', 'macOS'], value='macOS', # rows=10, description='OS:', disabled=False )
Select(description='OS:', index=2, options=('Linux', 'Windows', 'macOS'), value='macOS')

SelectionSlider

widgets.SelectionSlider( options=['scrambled', 'sunny side up', 'poached', 'over easy'], value='sunny side up', description='I like my eggs ...', disabled=False, continuous_update=False, orientation='horizontal', readout=True )
SelectionSlider(continuous_update=False, description='I like my eggs ...', index=1, options=('scrambled', 'sun…

SelectionRangeSlider

The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty.

import datetime dates = [datetime.date(2015, i, 1) for i in range(1, 13)] options = [(i.strftime('%b'), i) for i in dates] widgets.SelectionRangeSlider( options=options, index=(0, 11), description='Months (2015)', disabled=False )
SelectionRangeSlider(description='Months (2015)', index=(0, 11), options=(('Jan', datetime.date(2015, 1, 1)), …

ToggleButtons

widgets.ToggleButtons( options=['Slow', 'Regular', 'Fast'], description='Speed:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Description of slow', 'Description of regular', 'Description of fast'], # icons=['check'] * 3 )
ToggleButtons(description='Speed:', options=('Slow', 'Regular', 'Fast'), tooltips=('Description of slow', 'Des…

SelectMultiple

Multiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys.

widgets.SelectMultiple( options=['Apples', 'Oranges', 'Pears'], value=['Oranges'], #rows=10, description='Fruits', disabled=False )
SelectMultiple(description='Fruits', index=(1,), options=('Apples', 'Oranges', 'Pears'), value=('Oranges',))

String widgets

There are several widgets that can be used to display a string value. The Text, Textarea, and Combobox widgets accept input. The HTML and HTMLMath widgets display a string as HTML (HTMLMath also renders math). The Label widget can be used to construct a custom control label.

Text

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

Textarea

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

Combobox

widgets.Combobox( # value='John', placeholder='Choose Someone', options=['Paul', 'John', 'George', 'Ringo'], description='Combobox:', ensure_option=True, disabled=False )
Combobox(value='', description='Combobox:', ensure_option=True, options=('Paul', 'John', 'George', 'Ringo'), p…

Password

The Password widget hides user input on the screen. This widget is not a secure way to collect sensitive information because:

  • The contents of the Password widget are transmitted unencrypted.

  • If the widget state is saved in the notebook the contents of the Password widget is stored as plain text.

widgets.Password( value='password', placeholder='Enter password', description='Password:', disabled=False )
Password(description='Password:', placeholder='Enter password')

Label

The Label widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions.

widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()])
HBox(children=(Label(value='The $m$ in $E=mc^2$:'), FloatSlider(value=0.0)))

HTML

widgets.HTML( value="Hello <b>World</b>", placeholder='Some HTML', description='Some HTML', )
HTML(value='Hello <b>World</b>', description='Some HTML', placeholder='Some HTML')

HTML Math

widgets.HTMLMath( value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$", placeholder='Some HTML', description='Some HTML', )
HTMLMath(value='Some math and <i>HTML</i>: \\(x^2\\) and $$\\frac{x+1}{x-1}$$', description='Some HTML', place…

Image

file = open("images/WidgetArch.png", "rb") image = file.read() widgets.Image( value=image, format='png', width=300, height=400, )
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) /tmp/ipykernel_373466/1730779062.py in <module> ----> 1 file = open("images/WidgetArch.png", "rb") 2 image = file.read() 3 widgets.Image( 4 value=image, 5 format='png', FileNotFoundError: [Errno 2] No such file or directory: 'images/WidgetArch.png'

Button

button = widgets.Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check' # (FontAwesome names without the `fa-` prefix) ) button
Button(description='Click me', icon='check', style=ButtonStyle(), tooltip='Click me')

The icon attribute can be used to define an icon; see the fontawesome page for available icons. A callback function foo can be registered using button.on_click(foo). The function foo will be called when the button is clicked with the button instance as its single argument.

Output

The Output widget can capture and display stdout, stderr and rich output generated by IPython. For detailed documentation, see the [output widget examples](https://ipywidgets.readthedocs.io/en/latest/examples/Output Widget.html).

Play (Animation) widget

The Play widget is useful to perform animations by iterating on a sequence of integers with a certain speed. The value of the slider below is linked to the player.

play = widgets.Play( value=50, min=0, max=100, step=1, interval=500, description="Press play", disabled=False ) slider = widgets.IntSlider() widgets.jslink((play, 'value'), (slider, 'value')) widgets.HBox([play, slider])
HBox(children=(Play(value=50, description='Press play', interval=500), IntSlider(value=0)))

Tags input widget

The TagsInput widget is useful to for selecting/creating a list of tags. You can drag and drop tags to reorder them, limit them to a set of allowed values, or even prevent making duplicate tags.

tags = widgets.TagsInput( value=['pizza', 'fries'], allowed_tags=['pizza', 'fries', 'tomatoes', 'steak'], allow_duplicates=False ) tags
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_373466/235864657.py in <module> ----> 1 tags = widgets.TagsInput( 2 value=['pizza', 'fries'], 3 allowed_tags=['pizza', 'fries', 'tomatoes', 'steak'], 4 allow_duplicates=False 5 ) AttributeError: module 'ipywidgets' has no attribute 'TagsInput'
color_tags = widgets.ColorsInput( value=['red', '#2f6d30'], # allowed_tags=['red', 'blue', 'green'], # allow_duplicates=False ) color_tags
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_373466/1370919335.py in <module> ----> 1 color_tags = widgets.ColorsInput( 2 value=['red', '#2f6d30'], 3 # allowed_tags=['red', 'blue', 'green'], 4 # allow_duplicates=False 5 ) AttributeError: module 'ipywidgets' has no attribute 'ColorsInput'

Date picker

For a list of browsers that support the date picker widget, see the MDN article for the HTML date input field.

widgets.DatePicker( description='Pick a Date', disabled=False )
DatePicker(value=None, description='Pick a Date')

Time picker

For a list of browsers that support the time picker widget, see the MDN article for the HTML time input field.

widgets.TimePicker( description='Pick a Time', disabled=False )
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_373466/3401139348.py in <module> ----> 1 widgets.TimePicker( 2 description='Pick a Time', 3 disabled=False 4 ) AttributeError: module 'ipywidgets' has no attribute 'TimePicker'

Datetime picker

For a list of browsers that support the datetime picker widget, see the MDN article for the HTML datetime-local input field. For the browsers that do not support the datetime-local input, we try to fall back on displaying separate date and time inputs.

Time zones

There are two points worth to note with regards to timezones for datetimes:

This means that if the kernel and browser have different timezones, the default string serialization of the timezones might differ, but they will still represent the same point in time.

widgets.DatetimePicker( description='Pick a Time', disabled=False )
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_373466/3549670122.py in <module> ----> 1 widgets.DatetimePicker( 2 description='Pick a Time', 3 disabled=False 4 ) AttributeError: module 'ipywidgets' has no attribute 'DatetimePicker'

Color picker

widgets.ColorPicker( concise=False, description='Pick a color', value='blue', disabled=False )
ColorPicker(value='blue', description='Pick a color')

File Upload

The FileUpload allows to upload any type of file(s) into memory in the kernel.

widgets.FileUpload( accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False # True to accept multiple files upload else False )
FileUpload(value={}, description='Upload')

The upload widget exposes a value attribute that contains the files uploaded. The value attribute is a tuple with a dictionary for each uploaded file. For instance:

uploader = widgets.FileUpload() display(uploader) # upload something... # once a file is uploaded, use the `.value` attribute to retrieve the content: uploader.value #=> ( #=> { #=> 'name': 'example.txt', #=> 'type': 'text/plain', #=> 'size': 36, #=> 'last_modified': datetime.datetime(2020, 1, 9, 15, 58, 43, 321000, tzinfo=datetime.timezone.utc), #=> 'content': <memory at 0x10c1b37c8> #=> }, #=> )

Entries in the dictionary can be accessed either as items, as one would any dictionary, or as attributes:

uploaded_file = uploader.value[0] uploaded_file["size"] #=> 36 uploaded_file.size #=> 36

The contents of the file uploaded are in the value of the content key. They are a memory view:

uploaded_file.content #=> <memory at 0x10c1b37c8>

You can extract the content to bytes:

uploaded_file.content.tobytes() #=> b'This is the content of example.txt.\n'

If the file is a text file, you can get the contents as a string by decoding it:

import codecs codecs.decode(uploaded_file.content, encoding="utf-8") #=> 'This is the content of example.txt.\n'

You can save the uploaded file to the filesystem from the kernel:

with open("./saved-output.txt", "wb") as fp: fp.write(uploaded_file.content)

To convert the uploaded file into a Pandas dataframe, you can use a BytesIO object:

import io import pandas as pd pd.read_csv(io.BytesIO(uploaded_file.content))

If the uploaded file is an image, you can visualize it with an image widget:

widgets.Image(value=uploaded_file.content.tobytes())
Changes in *ipywidgets 8*:

The FileUpload changed significantly in ipywidgets 8:

  • The .value traitlet is now a list of dictionaries, rather than a dictionary mapping the uploaded name to the content. To retrieve the original form, use {f["name"]: f.content.tobytes() for f in uploader.value}.

  • The .data traitlet has been removed. To retrieve it, use [f.content.tobytes() for f in uploader.value].

  • The .metadata traitlet has been removed. To retrieve it, use [{k: v for k, v in f.items() if k != "content"} for f in w.value].

Warning: When using the `FileUpload` Widget, uploaded file content might be saved in the notebook if widget state is saved.

Controller

The Controller allows a game controller to be used as an input device.

widgets.Controller( index=0, )
Controller()

Container/Layout widgets

These widgets are used to hold other widgets, called children. Each has a children property that may be set either when the widget is created or later.

Box

items = [widgets.Label(str(i)) for i in range(4)] widgets.Box(items)
Box(children=(Label(value='0'), Label(value='1'), Label(value='2'), Label(value='3')))

HBox

items = [widgets.Label(str(i)) for i in range(4)] widgets.HBox(items)
HBox(children=(Label(value='0'), Label(value='1'), Label(value='2'), Label(value='3')))

VBox

items = [widgets.Label(str(i)) for i in range(4)] left_box = widgets.VBox([items[0], items[1]]) right_box = widgets.VBox([items[2], items[3]]) widgets.HBox([left_box, right_box])
HBox(children=(VBox(children=(Label(value='0'), Label(value='1'))), VBox(children=(Label(value='2'), Label(val…

GridBox

This box uses the HTML Grid specification to lay out its children in two dimensional grid. The example below lays out the 8 items inside in 3 columns and as many rows as needed to accommodate the items.

items = [widgets.Label(str(i)) for i in range(8)] widgets.GridBox(items, layout=widgets.Layout(grid_template_columns="repeat(3, 100px)"))
GridBox(children=(Label(value='0'), Label(value='1'), Label(value='2'), Label(value='3'), Label(value='4'), La…

Accordion

accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()], titles=('Slider', 'Text')) accordion
Accordion(children=(IntSlider(value=0), Text(value='')))

Tabs

In this example the children are set after the tab is created. Titles for the tabs are set in the same way they are for Accordion.

tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4'] children = [widgets.Text(description=name) for name in tab_contents] tab = widgets.Tab() tab.children = children tab.titles = [str(i) for i in range(len(children))] tab
Tab(children=(Text(value='', description='P0'), Text(value='', description='P1'), Text(value='', description='…

Stacked

The Stacked widget can have multiple children widgets as for Tab and Accordion, but only shows one at a time depending on the value of selected_index:

button = widgets.Button(description='Click here') slider = widgets.IntSlider() stacked = widgets.Stacked([button, slider]) stacked # will show only the button
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_373466/3506875831.py in <module> 1 button = widgets.Button(description='Click here') 2 slider = widgets.IntSlider() ----> 3 stacked = widgets.Stacked([button, slider]) 4 stacked # will show only the button AttributeError: module 'ipywidgets' has no attribute 'Stacked'

This can be used in combination with another selection-based widget to show different widgets depending on the selection:

dropdown = widgets.Dropdown(options=['button', 'slider']) widgets.jslink((dropdown, 'index'), (stacked, 'selected_index')) widgets.VBox([dropdown, stacked])
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_373466/75618139.py in <module> 1 dropdown = widgets.Dropdown(options=['button', 'slider']) ----> 2 widgets.jslink((dropdown, 'index'), (stacked, 'selected_index')) 3 widgets.VBox([dropdown, stacked]) NameError: name 'stacked' is not defined

Accordion, Tab, and Stacked use selected_index, not value

Unlike the rest of the widgets discussed earlier, the container widgets Accordion and Tab update their selected_index attribute when the user changes which accordion or tab is selected. That means that you can both see what the user is doing and programmatically set what the user sees by setting the value of selected_index.

Setting selected_index = None closes all of the accordions or deselects all tabs.

In the cells below try displaying or setting the selected_index of the tab and/or accordion.

tab.selected_index = 3
accordion.selected_index = None

Nesting tabs and accordions

Tabs and accordions can be nested as deeply as you want. If you have a few minutes, try nesting a few accordions or putting an accordion inside a tab or a tab inside an accordion.

The example below makes a couple of tabs with an accordion children in one of them

tab_nest = widgets.Tab() tab_nest.children = [accordion, accordion] tab_nest.titles = ('An accordion', 'Copy of the accordion') tab_nest
Tab(children=(Accordion(children=(IntSlider(value=0), Text(value='')), selected_index=None), Accordion(childre…

Index - [Back](Widget Basics.ipynb) - [Next](Output Widget.ipynb)