ipywidgets库包的使用教程
文章目录:
1 ipywidgets介绍与安装
1.1 ipywidgets介绍
ipywidgets 包可以实现 jupyter notebook 笔记本的交互式控件操作。也就是这个控件只能再jupyter notebook中使用,你再命令行下或其他IDE中时不能够使用的。它是基于网页的。
- 官方文档:https://ipywidgets.readthedocs.io/en/stable/index.html
- Github项目地址:https://github.com/jupyter-widgets/ipywidgets
widgets中的控件包括两部分:
UI/HTML element
,这是显示在output cell中的部分,通常是实例化后将其作为display函数的实参传递event handler
,控件的注册事件,通常做法是将一个定义好的python函数作为实参传递到控件的事件中
1.2 ipywidgets 安装
1、使用pip安装
pip install ipywidgets
2、使用conda安装
conda install -c conda-forge ipywidgets
2 ipywidgets的使用
2.1 interact() 函数,交互式控件
interact():
函数传入函数名及其参数即可实现交互式控件。 interact()函数的使用类似高阶函数
- 第一个参数:函数名
- 第二个参数:传入的数值
2.1.1 数值型参数
举例如下:
from ipywidgets import interact
def func(x):
return x**2
# 以滚动条的形式显示
interact(func, x=10)
# 以菜单的形式显示,传入参数列表
interact(func, x=[2,3,4,5])
# 以菜单的形式显示,参数参数字典
interact(func, x={"one":10, "two":20})
interact() 第二个参数
- 传入一个默认值x, 得到的取值范围为[-x, 3x],以滑动条的形式显示
- 传入的值为一个列表,以菜单的形式显示
框的左边显示的是参数名,或者说是变量名
2.1.2 布尔型参数
布尔型参数:一个复选框
def func2(flag):
if flag:
print("打上勾是True")
interact(func2, flag=True)
扫描二维码关注公众号,回复:
11321012 查看本文章
2.1.3 文本型参数
def func3(str):
return str
interact(func3, str="CSDN")
interact(func3, str=["YOU", "LOVE", "CSDN", "?"])
2.1.4 对控件进行参数设置
在interact()中使用参数IntSlider(min=-10,max=30,step=1,value=10) 设置最大最小值、步长,默认值,变量描述。
from ipywidgets import interact
import ipywidgets as widgets
def func(x):
return x**2
interact(func, x=widgets.IntSlider(min=1, max=45, step=2, value=10, description="Number"))
参考:
1、https://ipywidgets.readthedocs.io/en/stable/user_install.html
2、https://blog.csdn.net/liuqixuan1994/article/details/86708381
3、https://blog.csdn.net/xncsd/article/details/79518793
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠