将窗口小部件对象状态存储到ipython内核对象实例而不是对象类

问题描述 投票:0回答:1

stateful widget tutorial之后,我们可以创建一个简单的DOM小部件。这是python代码:

import ipywidgets.widgets as widgets
from traitlets import Unicode

class HelloWidget(widgets.DOMWidget):
    _view_name = Unicode('HelloView').tag(sync=True)
    _view_module = Unicode('hello').tag(sync=True)
    _view_module_version = Unicode('0.1.0').tag(sync=True)
    value = Unicode('Hello World!').tag(sync=True)

和javascript代码:

%%javascript
require.undef('hello');

define('hello', ["@jupyter-widgets/base"], function(widgets) {

    var HelloView = widgets.DOMWidgetView.extend({

        render: function() {
            this.el.textContent = this.model.get('value');
        },
    });

    return {
        HelloView : HelloView
    };
});

这与笔记本中的广告一样:

In [1]: HelloWidget()
Out [1]: Hello World!

现在,如果我想将小部件value状态存储到对象实例,我可以更改python代码,使其如下所示:

import ipywidgets.widgets as widgets
from traitlets import Unicode

class HelloWidget(widgets.DOMWidget):
    _view_name = Unicode('HelloView').tag(sync=True)
    _view_module = Unicode('hello').tag(sync=True)
    _view_module_version = Unicode('0.1.0').tag(sync=True)
    def __init__(self, s):
        super().__init__()
        self.value = Unicode(s).tag(sync=True)

但是,这不起作用;状态未按预期呈现到输出单元格(无输出):

In [1]: HelloWidget("Hello World!")
Out [1]: 

如何才能做到这一点?

javascript python jupyter-notebook ipython
1个回答
0
投票

我想出来了(感觉有点愚蠢)。

trailets.Unicode对象是描述符,因此必须附加到类对象HelloWidget。所以正确的代码如下:

import ipywidgets.widgets as widgets
from traitlets import Unicode

class HelloWidget(widgets.DOMWidget):
    _view_name = Unicode('HelloView').tag(sync=True)
    _view_module = Unicode('hello').tag(sync=True)
    _view_module_version = Unicode('0.1.0').tag(sync=True)
    value = Unicode().tag(sync=True) # value is set to an empty string as placeholder

    def __init__(self, s):
        super().__init__()
        self.value = s # initialize with a value here
© www.soinside.com 2019 - 2024. All rights reserved.