gpt4 book ai didi

python - 使用 ipywidgets 中的小部件的观察者模式

转载 作者:行者123 更新时间:2023-12-01 09:26:10 25 4
gpt4 key购买 nike

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

最佳答案

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

You need to use the Instance trait type. (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

关于python - 使用 ipywidgets 中的小部件的观察者模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com