【问题标题】:Observer pattern using a widget from ipywidgets使用来自 ipywidgets 的小部件的观察者模式
【发布时间】:2018-10-26 20:01:29
【问题描述】:

试图重现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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2012-08-19
      • 2016-02-20
      • 2023-04-10
      • 1970-01-01
      • 2013-01-01
      • 2013-02-12
      相关资源
      最近更新 更多