core.display¶
Module: core.display ¶
Inheritance diagram for IPython.core.display :
Top-level display functions for displaying object in different formats.
Classes¶
DisplayObject ¶
An object that wraps data to be displayed.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Image ¶
Create a display an PNG/JPEG image given raw data.
When this object is returned by an expression or passed to the display function, it will result in the image being displayed in the frontend.
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
format : unicode
The format of the image data (png/jpeg/jpg). If a filename or URL is given for format will be inferred from the filename extension.
embed : bool
Should the image data be embedded in the notebook using a data URI (True) or be loaded using an tag. Set this to True if you want the image to be viewable later with no internet connection. If a filename is given embed is always set to True.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Javascript ¶
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Pretty ¶
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Functions¶
Clear the output of the current cell receiving output.
Optionally, each of stdout/stderr or other non-stream data (e.g. anything produced by display()) can be excluded from the clear event.
By default, everything is cleared.
stdout : bool [default: True]
Whether to clear stdout.
stderr : bool [default: True]
Whether to clear stderr.
other : bool [default: True]
Whether to clear everything else that is not stdout/stderr (e.g. figures,images,HTML, any result of display()).
Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how.
objs : tuple of objects
The Python objects to display.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the format data dict. If this is set only the format types included in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclue in the format data dict. If this is set all format types will be computed, except for those included in this argument.
Display the HTML representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the Javascript representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw javascript data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the JPEG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw JPEG data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the JSON representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw json data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the LaTeX representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the PNG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw png data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the pretty (default) representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw text data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the SVG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw svg data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
core.display¶
Module: core.display ¶
Inheritance diagram for IPython.core.display :
Top-level display functions for displaying object in different formats.
Classes¶
DisplayObject ¶
An object that wraps data to be displayed.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Image ¶
Create a display an PNG/JPEG image given raw data.
When this object is returned by an expression or passed to the display function, it will result in the image being displayed in the frontend.
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
format : unicode
The format of the image data (png/jpeg/jpg). If a filename or URL is given for format will be inferred from the filename extension.
embed : bool
Should the image data be embedded in the notebook using a data URI (True) or be loaded using an tag. Set this to True if you want the image to be viewable later with no internet connection. If a filename is given embed is always set to True.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Javascript ¶
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Pretty ¶
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Create a display object given raw data.
When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for ‘image/png’ data. If the data is a URL, the data will first be downloaded and then displayed. If
data : unicode, str or bytes
The raw data or a URL to download the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
Reload the raw data from file or URL.
Functions¶
Clear the output of the current cell receiving output.
Optionally, each of stdout/stderr or other non-stream data (e.g. anything produced by display()) can be excluded from the clear event.
By default, everything is cleared.
stdout : bool [default: True]
Whether to clear stdout.
stderr : bool [default: True]
Whether to clear stderr.
other : bool [default: True]
Whether to clear everything else that is not stdout/stderr (e.g. figures,images,HTML, any result of display()).
Display a Python object in all frontends.
By default all representations will be computed and sent to the frontends. Frontends can decide which representation is used and how.
objs : tuple of objects
The Python objects to display.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the format data dict. If this is set only the format types included in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclue in the format data dict. If this is set all format types will be computed, except for those included in this argument.
Display the HTML representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the Javascript representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw javascript data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the JPEG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw JPEG data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the JSON representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw json data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the LaTeX representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw latex data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the PNG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw png data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the pretty (default) representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw text data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Display the SVG representation of an object.
objs : tuple of objects
The Python objects to display, or if raw=True raw svg data to display.
raw : bool
Are the data objects raw data or Python objects that need to be formatted before display? [default: False]
Добавляем в Jupyter Notebooks красоту и интерактивность
Многие используют в своей работе Jupyter Notebooks. Но с ростом сложности проекта появляются проблемы. В блокноте появляются ячейки с красными пометками для самого себя «перед запуском укажи число. » или «задай количество итераций исходя из. ». Какой-то откат к командной строке получается.
Да и вывод данных на экран не всегда воспринимается без пояснений сторонним человеком, который привык к красивым таблицам, картинкам и прочим современным элементам интерфейса.
Например, у нас есть данные по площадям городов и численности населения. Выведем их на экран в «традиционном виде»:
Современному, избалованному человеку такой формат отображения не всегда нравится. Нужно привести данные к более привычному табличному виду.
Можно использовать широко распространенную библиотеку pandas
Если по каким-то причинам использование pandas не устраивает, можно воспользоваться другой библиотекой или написать свою функцию.
Рассмотрим одну из таких библиотек — tabulate (https://pypi.org/project/tabulate/)
Для установки запустите из командной строки pip install tabulate
Можно вывести данные в «псевдографическом» виде.

Можно добавить заголовки

И индексы

tabulate позволяет получить визуально такой же результат как и pandas.
Можно написать свою функцию, которая потом обрастёт дополнительными возможностями.
Вывод изображений
Мы привыкли к пиктограммам и иконкам. Даже в прогнозе погоды мы видим картинки с солнышками и тучками. Чтобы добавить изображения в наши программы можно использовать библиотеку IPython. Ее функция Image позволяет работать с изображениями (PNG/JPEG/GIF), размещенными как локально, так и на интернет-ресурсах. Задавать их размеры.
Украшаем текст
Конечно, можно генерировать HTML напрямую, используя все его возможности:
А можно воспользоваться библиотекой termcolor. Она позмоляет не углубляясь в HTML задавать цвет текста и фона, задавать атрибуты шрифта. Описание библиотеки тут — pypi.org/project/termcolor
Отображаем прогресс выполнения задачи
Никому не нравится следить за ходом выполнения длительной задачи не понимая какая часть работы уже выполнена.
Видеть сколько осталось — гораздо приятнее (да-да, знаю, что скорость движения «червяка» может меняться).
Для установки используйте команды
Интерактивное взаимодействие с пользователем
Та же библиотека ipywidgets позволяет не только отображать, но и вносить информацию.
Самый, наверное, простой пример взаимодействия с пользователем — это реакция на нажатие кнопки. Библиотека ipywidgets позволяет создать кнопку с заданными параметрами (текстом, стилем и размерами) и назначить функцию-обработчик ее нажатия.
Размер кнопки задается при помощи свойства layout
Для удобного ввода пользователем чисел и дат есть компоненты FloatSlider и DatePicker.
Чтобы отловить момент изменения значений, нужно использовать событие observe
Проверим доступ к текущему значению:
Для выбора одного значения из нескольких вариантов есть список RadioButtons, выпадающий список Dropdown и группа кнопок ToggleButtons. value и observe для этих компонентов используются точно так же.
Значения можно задавать как в виде перечня строчных величин, так и в виде списка кортежей.
Попробуем самый простой вариант, со значениями в виде списка строк.
Выведем на экран значение:
В этом режиме значением rButtons1.value является строка.
Пробуем второй вариант задания списка значений:
В этом режиме значением rButtons2.value является число, соответствующее выбранному значению.
Аналогично работает выпадающий список (Dropdown)
Для ввода булевых значений можно использовать Checkbox и ToggleButton. У них есть уже знакомые нам value и observe.
Для ввода многострочного текста служет компонент Textarea
ИИ (интерфейсные изыски)
Когда элементов интерфейса становится слишком много, хочется пойти по пути десктопных приложений и объединить отдельные элементы в обособленные группы.
Для этого нам пригодятся Accordion и Tab.
Библиотека ipywidgets не ограничивается элементами, которые я перечислил. В ней еще масса полезных вещей, которые могут сделать программы в Jupyter Notebooks более привлекательными.
























