尝试在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
答案 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