使用来自ipywidgets的小部件的观察者模式

时间:2018-05-16 17:01:06

标签: python ipython jupyter-notebook observer-pattern ipywidgets

尝试在http://traitlets.readthedocs.io/en/stable/using_traitlets.html#observe中重现该示例,但是使用窗口小部件作为类属性,行为会发生变化,并且不会在更改中发现

from ipywidgets import Label
from traitlets import HasTraits, Unicode, observe
class Foo(HasTraits):
    bar = Label()
    baz = Unicode()

    @observe('bar')
    def _observe_bar(self, change):
        print(change['old'])
        print(change['new'])

f = Foo()
f.bar = Label('hello')  # No printing

1 个答案:

答案 0 :(得分:1)

我从Sylvain Corlay(https://github.com/jupyter-widgets/ipywidgets/issues/2078)获得了ipywidgets repo的问题跟踪器的答案

  

您需要使用Instance特质类型。 (Instance(Label)

所以

from ipywidgets import Label
from traitlets import HasTraits, Unicode, observe, Instance
class Foo(HasTraits):
    bar = Instance(Label)
    baz = Unicode()

    @observe('bar')
    def _observe_bar(self, change):
        print(change['old'])
        print(change['new'])

f = Foo()
f.bar = Label('hello')  # No printing