首页 > 解决方案 > 获取类中的ipywidget按钮以通过self访问类参数?

问题描述

我正在编写一个类,我想包含多个可以在 Jupyter 笔记本中显示的小部件。这些小部件应该调用更新类参数的类方法。我连接到 ipywidget 事件的函数需要访问类实例,我通过 self 思考,但我不知道如何让这种通信正常工作。

这是一个最小的例子:

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 类的方法,或者是否有更好的方法可以构建此代码以简化这些组件之间的通信?

标签: pythonipywidgets

解决方案


  1. 按钮小部件和 on_click 应该在 init 方法中创建(或初始化)。
  2. on_click 方法生成一个发送给函数的参数,但在这种情况下不需要它,所以我只是在 button_pressed 函数中放了一个 *args。
  3. 不需要显示调用。
  4. 在类中调用函数时,必须使用 self. 函数名。这包括函数调用on_clickobserve
  5. 在这种情况下,您不需要在 init 函数中生成随机数。

这里有一些类中的 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

推荐阅读