我正在编写一个我想包含多个可以在Jupyter笔记本中显示的小部件的类。这些小部件应调用更新类参数的类方法。我认为通过self可以连接到ipywidget事件的函数需要访问该类实例,但是我不知道如何使这种通信正常工作。
这是一个最小的例子:
import numpy as np
import ipywidgets as widgets
class Test(object):
def __init__(self):
self.val = np.random.rand()
display(self._random_button)
_random_button = widgets.Button(
description='randomize self.val'
)
def update_random(self):
self.val = np.random.rand()
print(self.val)
def button_pressed(self):
self.update_random()
_random_button.on_click(button_pressed)
我看到了button_pressed()
函数如何将Button实例视为self
,给出了“ AttributeError:'Button'对象没有属性'update_random'”。
是否有一种方法可以通过属于该类的按钮访问Test类的方法,还是有一种更好的方法来构造此代码以简化这些组件之间的通信?
答案 0 :(得分:1)
on_click
或observe
此处的类中有Jupyter小部件的一些示例:https://github.com/bloomberg/bqplot/tree/master/examples/Applications
import numpy as np
import ipywidgets as widgets
class Test(object):
def __init__(self):
self.random_button = widgets.Button(
description='randomize self.val')
self.random_button.on_click(self.button_pressed)
def update_random(self):
self.val = np.random.rand()
print(self.val)
def button_pressed(self,*args):
self.update_random()
buttonObject = Test()
# display(buttonObject.random_button) # display works but is not required if on the last line in Jupyter cell.
buttonObject.random_button # Widget to be dispalyed - must last last line in cell
答案 1 :(得分:1)
使用JupyterLab时,如果您希望输出显示在笔记本单元中,而不是笔记本日志中,则需要对@DougR的出色答案进行细微调整:
import numpy as np
import ipywidgets as widgets
# create an output widget
rand_num_output = widgets.Output()
class Test(object):
def __init__(self):
self.random_button = widgets.Button(
description='randomize self.val')
self.random_button.on_click(self.button_pressed)
def update_random(self):
# clear the output on every click of randomize self.val
rand_num_output.clear_output()
# execute function so it gets captured in output widget view
with rand_num_output:
self.val = np.random.rand()
print(self.val)
def button_pressed(self,*args):
self.update_random()
buttonObject = Test()
# display(buttonObject.random_button) # display works but is not required if on the last line in Jupyter cell.
widgets.HBox([buttonObject.random_button, rand_num_output]) # Widget to be dispalyed - must last last line in cell, add output widget