使用JupyterLab ipywidgets创建参数保存按钮


interact函数出现在

ipywidgets教程(使用Interact)中。使用它动态地操作matplotlib图很有趣。

我认为如果可以保存交互滑动条所使用的参数会很方便,但是我记了一下,因为这花费了很多时间。

环境

  • JupyterLab 0.35.4
  • ipywidgets 7.4.2
  • Python 3.5.2

*为了在Jupyter Lab中使用ipywidget,必须与jupyter Notebook分开安装。单击此处了解详细信息。

1
2
3
$ jupyter labextension install @jupyter-widgets/jupyterlab-manager
# JupyterLab 0.35.4で使うためにはバージョン指定が必要
# jupyter labextension install @jupyter-widgets/[email protected]

save_params.ipynb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
%matplotlib inline
import ipywidgets as widgets
from IPython.display import display
import numpy as np
import matplotlib.pyplot as plt

# セーブボタン
button = widgets.Button(description='save')
display(button)
# ボタンをクリックしたときのprint文のために必要
# JupyterLabを使っていない場合は不要
output = widgets.Output()
display(output)

# 直前に登録したcallback
callback = None

@widgets.interact(
    a=(0, 3, 0.1),
    b=(-3, 3, 0.1)
)
def plot_sin_curve(a=1, b=0):
    x = np.arange(-3, 3, 0.1)
    y = np.sin(a * x + b)
    plt.plot(x, y)

    # ボタンをクリックしたときの処理
    # JupyterLabでは通常widgetの出力は表示されないのでキャプチャする
    @output.capture(clear_output=True)
    def save_params(btn):
        content = 'a = {}, b = {}'.format(a, b)
        print('{} is saved!'.format(content))
        # ボタンをクリックするたびにaおよびbの値をparams.txtに追記
        with open('params.txt', mode='a') as f:
            f.write('{}\n'.format(content))

    # 直前のcallbackを削除する
    global callback
    if callback is not None:
        button.on_click(callback, remove=True)

    # クリックしたときの動作を登録
    button.on_click(save_params)
    callback = save_params

重点是
1. JupyterLab需要使用ipywidgets.Output()来捕获小部件的输出
2.如果您多次调用窗口小部件的on_click,则每次都会附加回调,因此如果不需要它,请删除它

有两点,

参考文献

  • https://github.com/jupyter-widgets/ipywidgets/issues/2068
  • https://github.com/jupyter-widgets/ipywidgets/issues/2103