Jupyter Notebook教程IPyWidgets库

Jupyter Notebook教程IPyWidgets库

Jupyter Notebook教程IPyWidgets库

Jupyter Notebook教程IPyWidgets库

  IPyWidgets是用于Jupyter笔记本的HTML交互式小部件的Python库。库中的每个UI元素都可以响应事件并调用指定的事件处理函数。它们增强了Jupyter笔记本应用程序的交互功能。

  推荐:零基础如何开始学习Python

Widget List小部件列表

  如果您的安装中没有ipywidgets,请运行:

pip install ipywidgets

  为了将小部件合并到笔记本中,我们必须导入以下模块,如下所示-

from ipywidgets import widgets

  这里解释了一些基本的IPyWidgets-

Text input

  widgets.text()函数在笔记本中呈现小部件。它类似于HTML中的文本框表单元素。此小部件的对象具有on_submit()方法,该方法侦听文本字段的活动并可以调用作为参数提供的事件处理程序。

  推荐:如何使用Python破解ZIP压缩文件密码

Button

IPyWidgets库buttons

  这个小部件类似于HTML按钮。当它被点击时,事件由on_click()方法注册,该方法调用点击事件处理程序。

from ipywidgets import widgets
mybtn = widgets.Button(
    description='Say Hello',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Say Hi',
    icon='check' # (FontAwesome names without the `fa-` prefix)
)

def sayhello(val):
    print("Hello {}".format(val))

@mybtn.on_click

def sayhello_onclick(a):
    sayhello(txtval.value)
mybtn

Label

  此小部件可用于在笔记本中显示不可编辑的文本。

Slider

IPyWidgets库silder

  显示递增整数值的滑块控件。还有一个Float Slider和Int Range Slider(在范围之间更改整数)

from ipywidgets import widgets
sliderval = widgets.IntSlider(
    value=0,
    min=0,
    max=100,
    step=10,
    description='Slider Value',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='d'
)
sliderval

display()

  ipywidgets模块中的这个函数在笔记本的输入单元格中呈现小部件对象。

  推荐:11个流行的Python存储库

Interact

  此函数根据给定的数据参数类型自动呈现一个小部件。该函数的第一个参数是事件处理程序,第二个参数是传递给事件处理程序本身的值。

IPyWidgets库交互

  以下示例显示了三个标签小部件、两个文本小部件和一个带有“添加”标题的按钮。单击按钮时,两个文本输入字段中的数字总和将显示在最下方的标签上。

from ipywidgets import widgets
L1=widgets.Label('First number') 
display(L1)
text1=widgets.Text()
display(text1) 
L2=widgets.Label('second number')
display(L2)
text2=widgets.Text()
display(text2)
btn=widgets.Button (description="add")
display(btn)
L3=widgets.Label()
display(L3)
def add(b):
    x=int(text1.value)
    y=int(text2.value)
    L3.value='result= '+str(x+y)
btn.on_click(add)

总结

  以上是晓得博客为你介绍的Jupyter Notebook教程IPyWidgets库的全部内容,希望在阅读本文时会有所收获,相信Jupyter小部件的潜力,并希望这篇文章能够帮助你。

  推荐:Jupyter Notebook教程


晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Jupyter Notebook教程IPyWidgets库

转载请保留链接:https://www.pythonthree.com/jupyter-notebook-ipywidgets/

滚动至顶部