{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[Index](Index.ipynb) - [Back](Widget Basics.ipynb) - [Next](Output Widget.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Widget List" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ipywidgets as widgets" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Numeric widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### IntSlider \n", "- 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.\n", "- The slider's label is defined by `description` parameter \n", "- The slider's `orientation` is either 'horizontal' (default) or 'vertical'\n", "- `readout` displays the current value of the slider next to it. The options are **True** (default) or **False** \n", " - `readout_format` specifies the format function used to represent slider value. The default is '.2f'\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.IntSlider(\n", " value=7,\n", " min=0,\n", " max=10,\n", " step=1,\n", " description='Test:',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='horizontal',\n", " readout=True,\n", " readout_format='d'\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### FloatSlider " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatSlider(\n", " value=7.5,\n", " min=0,\n", " max=10.0,\n", " step=0.1,\n", " description='Test:',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='horizontal',\n", " readout=True,\n", " readout_format='.1f',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An example of sliders **displayed vertically**." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatSlider(\n", " value=7.5,\n", " min=0,\n", " max=10.0,\n", " step=0.1,\n", " description='Test:',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='vertical',\n", " readout=True,\n", " readout_format='.1f',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### FloatLogSlider" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatLogSlider(\n", " value=10,\n", " base=10,\n", " min=-10, # max exponent of base\n", " max=10, # min exponent of base\n", " step=0.2, # exponent step\n", " description='Log Slider'\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### IntRangeSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.IntRangeSlider(\n", " value=[5, 7],\n", " min=0,\n", " max=10,\n", " step=1,\n", " description='Test:',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='horizontal',\n", " readout=True,\n", " readout_format='d',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### FloatRangeSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatRangeSlider(\n", " value=[5, 7.5],\n", " min=0,\n", " max=10.0,\n", " step=0.1,\n", " description='Test:',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='horizontal',\n", " readout=True,\n", " readout_format='.1f',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### IntProgress" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.IntProgress(\n", " value=7,\n", " min=0,\n", " max=10,\n", " description='Loading:',\n", " bar_style='', # 'success', 'info', 'warning', 'danger' or ''\n", " style={'bar_color': 'maroon'},\n", " orientation='horizontal'\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### FloatProgress" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatProgress(\n", " value=7.5,\n", " min=0,\n", " max=10.0,\n", " description='Loading:',\n", " bar_style='info',\n", " style={'bar_color': '#ffff00'},\n", " orientation='horizontal'\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter.\n", "\n", "### BoundedIntText" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.BoundedIntText(\n", " value=7,\n", " min=0,\n", " max=10,\n", " step=1,\n", " description='Text:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### BoundedFloatText" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.BoundedFloatText(\n", " value=7.5,\n", " min=0,\n", " max=10.0,\n", " step=0.1,\n", " description='Text:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### IntText" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.IntText(\n", " value=7,\n", " description='Any:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### FloatText" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FloatText(\n", " value=7.5,\n", " description='Any:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Boolean widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are three widgets that are designed to display a boolean value." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ToggleButton" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.ToggleButton(\n", " value=False,\n", " description='Click me',\n", " disabled=False,\n", " button_style='', # 'success', 'info', 'warning', 'danger' or ''\n", " tooltip='Description',\n", " icon='check' # (FontAwesome names without the `fa-` prefix)\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Checkbox \n", "- `value` specifies the value of the checkbox\n", "- `indent` parameter places an indented checkbox, aligned with other controls. Options are **True** (default) or **False** \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Checkbox(\n", " value=False,\n", " description='Check me',\n", " disabled=False,\n", " indent=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Valid\n", "\n", "The valid widget provides a read-only indicator." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Valid(\n", " value=False,\n", " description='Valid!',\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Selection widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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`).\n", "\n", "
\n", "Changes in *ipywidgets 8*:\n", " \n", "Selection widgets no longer accept a dictionary of options. Pass a list of key-value pairs instead.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Dropdown" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Dropdown(\n", " options=['1', '2', '3'],\n", " value='2',\n", " description='Number:',\n", " disabled=False,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following is also valid, displaying the words `'One', 'Two', 'Three'` as the dropdown choices but returning the values `1, 2, 3`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Dropdown(\n", " options=[('One', 1), ('Two', 2), ('Three', 3)],\n", " value=2,\n", " description='Number:',\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### RadioButtons" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.RadioButtons(\n", " options=['pepperoni', 'pineapple', 'anchovies'],\n", "# value='pineapple', # Defaults to 'pineapple'\n", "# layout={'width': 'max-content'}, # If the items' names are long\n", " description='Pizza topping:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### With dynamic layout and very long labels" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Box(\n", " [\n", " widgets.Label(value='Pizza topping with a very long label:'), \n", " widgets.RadioButtons(\n", " options=[\n", " 'pepperoni', \n", " 'pineapple', \n", " 'anchovies', \n", " 'and the long name that will fit fine and the long name that will fit fine and the long name that will fit fine '\n", " ],\n", " layout={'width': 'max-content'}\n", " )\n", " ]\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Select" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Select(\n", " options=['Linux', 'Windows', 'macOS'],\n", " value='macOS',\n", " # rows=10,\n", " description='OS:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SelectionSlider" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.SelectionSlider(\n", " options=['scrambled', 'sunny side up', 'poached', 'over easy'],\n", " value='sunny side up',\n", " description='I like my eggs ...',\n", " disabled=False,\n", " continuous_update=False,\n", " orientation='horizontal',\n", " readout=True\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SelectionRangeSlider\n", "\n", "The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import datetime\n", "dates = [datetime.date(2015, i, 1) for i in range(1, 13)]\n", "options = [(i.strftime('%b'), i) for i in dates]\n", "widgets.SelectionRangeSlider(\n", " options=options,\n", " index=(0, 11),\n", " description='Months (2015)',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### ToggleButtons" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.ToggleButtons(\n", " options=['Slow', 'Regular', 'Fast'],\n", " description='Speed:',\n", " disabled=False,\n", " button_style='', # 'success', 'info', 'warning', 'danger' or ''\n", " tooltips=['Description of slow', 'Description of regular', 'Description of fast'],\n", "# icons=['check'] * 3\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SelectMultiple\n", "Multiple values can be selected with shift and/or ctrl (or command) pressed and mouse clicks or arrow keys." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.SelectMultiple(\n", " options=['Apples', 'Oranges', 'Pears'],\n", " value=['Oranges'],\n", " #rows=10,\n", " description='Fruits',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## String widgets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Text" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Text(\n", " value='Hello World',\n", " placeholder='Type something',\n", " description='String:',\n", " disabled=False \n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Textarea" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Textarea(\n", " value='Hello World',\n", " placeholder='Type something',\n", " description='String:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combobox" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Combobox(\n", " # value='John',\n", " placeholder='Choose Someone',\n", " options=['Paul', 'John', 'George', 'Ringo'],\n", " description='Combobox:',\n", " ensure_option=True,\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Password\n", "\n", "The `Password` widget hides user input on the screen. **This widget is not a secure way to collect sensitive information because:**\n", "\n", "+ The contents of the `Password` widget are transmitted unencrypted.\n", "+ If the widget state is saved in the notebook the contents of the `Password` widget is stored as plain text." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Password(\n", " value='password',\n", " placeholder='Enter password',\n", " description='Password:',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Label\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.HBox([widgets.Label(value=\"The $m$ in $E=mc^2$:\"), widgets.FloatSlider()])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### HTML" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.HTML(\n", " value=\"Hello World\",\n", " placeholder='Some HTML',\n", " description='Some HTML',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### HTML Math" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.HTMLMath(\n", " value=r\"Some math and HTML: \\(x^2\\) and $$\\frac{x+1}{x-1}$$\",\n", " placeholder='Some HTML',\n", " description='Some HTML',\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Image" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "file = open(\"images/WidgetArch.png\", \"rb\")\n", "image = file.read()\n", "widgets.Image(\n", " value=image,\n", " format='png',\n", " width=300,\n", " height=400,\n", ")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Button" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "button = widgets.Button(\n", " description='Click me',\n", " disabled=False,\n", " button_style='', # 'success', 'info', 'warning', 'danger' or ''\n", " tooltip='Click me',\n", " icon='check' # (FontAwesome names without the `fa-` prefix)\n", ")\n", "button" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `icon` attribute can be used to define an icon; see the [fontawesome](https://fontawesome.com/icons) page for available icons. \n", "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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Output\n", "\n", "The `Output` widget can capture and display stdout, stderr and [rich output generated by IPython](http://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#module-IPython.display). For detailed documentation, see the [output widget examples](https://ipywidgets.readthedocs.io/en/latest/examples/Output Widget.html)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Play (Animation) widget" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "play = widgets.Play(\n", " value=50,\n", " min=0,\n", " max=100,\n", " step=1,\n", " interval=500,\n", " description=\"Press play\",\n", " disabled=False\n", ")\n", "slider = widgets.IntSlider()\n", "widgets.jslink((play, 'value'), (slider, 'value'))\n", "widgets.HBox([play, slider])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tags input widget" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tags = widgets.TagsInput(\n", " value=['pizza', 'fries'],\n", " allowed_tags=['pizza', 'fries', 'tomatoes', 'steak'],\n", " allow_duplicates=False\n", ")\n", "tags" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "color_tags = widgets.ColorsInput(\n", " value=['red', '#2f6d30'],\n", " # allowed_tags=['red', 'blue', 'green'],\n", " # allow_duplicates=False\n", ")\n", "color_tags" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Date picker\n", "\n", "For a list of browsers that support the date picker widget, see the [MDN article for the HTML date input field](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Browser_compatibility)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.DatePicker(\n", " description='Pick a Date',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Time picker\n", "\n", "For a list of browsers that support the time picker widget, see the [MDN article for the HTML time input field](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#Browser_compatibility)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.TimePicker(\n", " description='Pick a Time',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Datetime picker\n", "\n", "For a list of browsers that support the datetime picker widget, see the [MDN article for the HTML datetime-local input field](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local#Browser_compatibility). For the browsers that do not support the datetime-local input, we try to fall back on displaying separate date and time inputs.\n", "\n", "### Time zones\n", "\n", "There are two points worth to note with regards to timezones for datetimes:\n", "- The browser always picks datetimes using *its* timezone.\n", "- 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).\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.DatetimePicker(\n", " description='Pick a Time',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Color picker" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.ColorPicker(\n", " concise=False,\n", " description='Pick a color',\n", " value='blue',\n", " disabled=False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## File Upload\n", "\n", "The `FileUpload` allows to upload any type of file(s) into memory in the kernel." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.FileUpload(\n", " accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'\n", " multiple=False # True to accept multiple files upload else False\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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:\n", "\n", "```python\n", "uploader = widgets.FileUpload()\n", "display(uploader)\n", "\n", "# upload something...\n", "\n", "# once a file is uploaded, use the `.value` attribute to retrieve the content:\n", "uploader.value\n", "#=> (\n", "#=> {\n", "#=> 'name': 'example.txt',\n", "#=> 'type': 'text/plain',\n", "#=> 'size': 36,\n", "#=> 'last_modified': datetime.datetime(2020, 1, 9, 15, 58, 43, 321000, tzinfo=datetime.timezone.utc), \n", "#=> 'content': \n", "#=> },\n", "#=> )\n", "```\n", "\n", "Entries in the dictionary can be accessed either as items, as one would any dictionary, or as attributes:\n", "\n", "```\n", "uploaded_file = uploader.value[0]\n", "uploaded_file[\"size\"]\n", "#=> 36\n", "uploaded_file.size\n", "#=> 36\n", "```\n", "\n", "The contents of the file uploaded are in the value of the `content` key. They are a [memory view](https://docs.python.org/3/library/stdtypes.html#memory-views):\n", "\n", "```python\n", "uploaded_file.content\n", "#=> \n", "```\n", "\n", "You can extract the content to bytes:\n", "\n", "```python\n", "uploaded_file.content.tobytes()\n", "#=> b'This is the content of example.txt.\\n'\n", "```\n", "\n", "If the file is a text file, you can get the contents as a string by [decoding it](https://docs.python.org/3/library/codecs.html):\n", "\n", "```python\n", "import codecs\n", "codecs.decode(uploaded_file.content, encoding=\"utf-8\")\n", "#=> 'This is the content of example.txt.\\n'\n", "```\n", "\n", "You can save the uploaded file to the filesystem from the kernel:\n", "\n", "```python\n", "with open(\"./saved-output.txt\", \"wb\") as fp:\n", " fp.write(uploaded_file.content)\n", "```\n", "\n", "To convert the uploaded file into a Pandas dataframe, you can use a [BytesIO object](https://docs.python.org/3/library/io.html#binary-i-o):\n", "\n", "```python\n", "import io\n", "import pandas as pd\n", "pd.read_csv(io.BytesIO(uploaded_file.content))\n", "```\n", "\n", "If the uploaded file is an image, you can visualize it with an [image](#Image) widget:\n", "\n", "```python\n", "widgets.Image(value=uploaded_file.content.tobytes())\n", "```\n", "\n", "
\n", "Changes in *ipywidgets 8*:\n", " \n", "The `FileUpload` changed significantly in ipywidgets 8:\n", " \n", "- 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}`.\n", "- The `.data` traitlet has been removed. To retrieve it, use `[f.content.tobytes() for f in uploader.value]`.\n", "- 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]`.\n", "
\n", "\n", "
\n", "Warning: When using the `FileUpload` Widget, uploaded file content might be saved in the notebook if widget state is saved.\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Controller\n", "\n", "The `Controller` allows a game controller to be used as an input device." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widgets.Controller(\n", " index=0,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Container/Layout widgets\n", "\n", "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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Box" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "items = [widgets.Label(str(i)) for i in range(4)]\n", "widgets.Box(items)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### HBox" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "items = [widgets.Label(str(i)) for i in range(4)]\n", "widgets.HBox(items)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### VBox" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "items = [widgets.Label(str(i)) for i in range(4)]\n", "left_box = widgets.VBox([items[0], items[1]])\n", "right_box = widgets.VBox([items[2], items[3]])\n", "widgets.HBox([left_box, right_box])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### GridBox\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "items = [widgets.Label(str(i)) for i in range(8)]\n", "widgets.GridBox(items, layout=widgets.Layout(grid_template_columns=\"repeat(3, 100px)\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accordion" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()], titles=('Slider', 'Text'))\n", "accordion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tabs\n", "\n", "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`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']\n", "children = [widgets.Text(description=name) for name in tab_contents]\n", "tab = widgets.Tab()\n", "tab.children = children\n", "tab.titles = [str(i) for i in range(len(children))]\n", "tab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Stacked\n", "\n", "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``:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "button = widgets.Button(description='Click here')\n", "slider = widgets.IntSlider()\n", "stacked = widgets.Stacked([button, slider])\n", "stacked # will show only the button" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can be used in combination with another selection-based widget to show different widgets depending on the selection:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dropdown = widgets.Dropdown(options=['button', 'slider'])\n", "widgets.jslink((dropdown, 'index'), (stacked, 'selected_index'))\n", "widgets.VBox([dropdown, stacked])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accordion, Tab, and Stacked use `selected_index`, not value\n", "\n", "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`.\n", "\n", "Setting `selected_index = None` closes all of the accordions or deselects all tabs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the cells below try displaying or setting the `selected_index` of the `tab` and/or `accordion`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tab.selected_index = 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "accordion.selected_index = None" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Nesting tabs and accordions\n", "\n", "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. \n", "\n", "The example below makes a couple of tabs with an accordion children in one of them" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tab_nest = widgets.Tab()\n", "tab_nest.children = [accordion, accordion]\n", "tab_nest.titles = ('An accordion', 'Copy of the accordion')\n", "tab_nest" ] }, { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[Index](Index.ipynb) - [Back](Widget Basics.ipynb) - [Next](Output Widget.ipynb)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 4 }