!pip list | grep ipywidget
ipywidgets 8.1.3
Benedict Thekkel
from IPython.display import IFrame
# Specify the path to your HTML file
html_file_path = 'export.html'
# Display the HTML file in the notebook
IFrame(src=html_file_path, width='100%', height=600)
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.
value
. Lower and upper bounds are defined by min
and max
, and the value can be incremented according to the step
parameter.description
parameterorientation
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’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',
)
An example of sliders displayed vertically.
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.FloatProgress(
value=7.5,
min=0,
max=10.0,
description='Loading:',
bar_style='info',
style={'bar_color': '#ffff00'},
orientation='horizontal'
)
The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter.
There are three widgets that are designed to display a boolean value.
value
specifies the value of the checkboxindent
parameter places an indented checkbox, aligned with other controls. Options are True (default) or FalseThe valid widget provides a read-only indicator.
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
).
The following is also valid, displaying the words 'One', 'Two', 'Three'
as the dropdown choices but returning the values 1, 2, 3
.
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
)
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'}
)
]
)
The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty.
Multiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys.
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.
The Password
widget hides user input on the screen. This widget is not a secure way to collect sensitive information because:
Password
widget are transmitted unencrypted.Password
widget is stored as plain text.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.
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
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.
The Output
widget can capture and display stdout, stderr and rich output generated by IPython. For detailed documentation, see the output widget examples.
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.
The TagsInput
widget is useful 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.
The ColorsInput
widget is useful for selecting/creating a list of colors. You can drag and drop colors to reorder them, limit them to a set of allowed values, or even prevent making duplicate colors.
The FloatInputs
and IntsInput
widgets enable creating a list of float or integer numbers.
For a list of browsers that support the date picker widget, see the MDN article for the HTML date input field.
For a list of browsers that support the time picker widget, see the MDN article for the HTML time input field.
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.
There are two points worth to note with regards to timezones for datetimes: - The browser always picks datetimes using its timezone. - The kernel always gets the datetimes in the default system timezone of the kernel (see https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone with None
as the argument).
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.
In some cases you might want to be able to pick naive datetime objects, i.e. timezone-unaware datetimes. To quote the Python 3 docs:
Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
This is useful if you need to compare the picked datetime to naive datetime objects, as Python will otherwise complain!
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
)
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:
You can extract the content to bytes:
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:
To convert the uploaded file into a Pandas dataframe, you can use a BytesIO object:
If the uploaded file is an image, you can visualize it with an image widget:
Changes in ipywidgets 8:
The FileUpload
changed significantly in ipywidgets 8:
.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}
..data
traitlet has been removed. To retrieve it, use [f.content.tobytes() for f in uploader.value]
..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.
The Controller
allows a game controller to be used as an input device.
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.
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.
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
.
The Stack
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()
stack = widgets.Stack([button, slider], selected_index=0)
stack # will show only the button
This can be used in combination with another selection-based widget to show different widgets depending on the selection:
selected_index
, not valueUnlike 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
.
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