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)
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
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠