Jupyter 简明教程
Jupyter Notebook - IPyWidgets
IPyWidgets 是一个用于 Jupyter 笔记本的 HTML 交互式小部件的 Python 库。库中的每个 UI 元素都可以响应事件并调用指定的事件处理程序函数。它们增强了 Jupyter 笔记本应用程序的交互功能。
IPyWidgets is a Python library of HTML interactive widgets for Jupyter notebook. Each UI element in the library can respond to events and invokes specified event handler functions. They enhance the interactive feature of Jupyter notebook application.
为了在笔记本中加入小部件,我们必须导入以下模块,如下图所示 −
In order to incorporate widgets in the notebook, we have to import the following module as shown below −
from ipywidgets import widgets
一些基本的 IPyWidgets 在此处解释 −
Some basic IPyWidgets are explained here −
Text input
widgets.text() 函数在笔记本中渲染小部件。它类似于 HTML 中的文本框表单元素。此小部件的对象具有 on_submit() 方法,该方法会侦听文本字段的活动并且能够调用作为参数给它的事件处理程序。
The widgets.text() function renders widgets in the notebook. It is similar to text box form element in HTML. The object of this widget has on_submit() method which listens to activity of the text field and can invoke event handler given as an argument to it.
Button
这个小组件类似于 HTML 按钮。当它被点击时,事件由 on_click() 方法注册,该方法调用点击事件处理程序。
This widget is similar to HTML button. When it is clicked, the event is registered by on_click() method which calls the click event handler.
IntSlider
一个滑块控件,显示增量整数值。还有 FloatSlider 和 IntRangeSlider(改变范围内的整数)
A slider control which displays the incrementing integer values. There is also a FloatSlider and IntRangeSlider (changing integer between a range)
display()
这个来自 ipywidgets 模块的函数在笔记本的输入单元格中渲染小组件对象。
This function from ipywidgets module renders the widget object in notebook’s input cell.
Interact
这个函数根据给定的数据参数类型自动渲染一个控件。该函数的第一个参数是事件处理程序,第二个是传递给事件处理程序本身的一个值。
This function automatically renders a widget depending upon type of data argument given to it. First argument to this function is the event handler and second is a value passed to event handler itself.
下面的例子显示了三个标签控件、两个文本控件和一个带“添加”标题的按钮。当点击这个按钮时,两个文本输入框中的数字之和显示在最底部的标签上。
Following example shows three label widgets, two text widgets and a button with ‘add’ caption. When the button is clicked, sum of numbers in two text input fields is displayed on the lowermost label.