[英]Store widget object state to an ipython kernel object instance rather than the object class
Following the stateful widget tutorial , we can create a simple DOM widget. 遵循有状态的小部件教程之后 ,我们可以创建一个简单的DOM小部件。 Here is the python code:
这是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)
And the javascript code: 和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
};
});
This works as advertised in the notebook: 可以在笔记本上做广告:
In [1]: HelloWidget()
Out [1]: Hello World!
Now, if I want to store the widget value
state to the object instance, I can change the python code so it looks like the following: 现在,如果我想将小部件的
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)
However, this does not work; 但是,这不起作用。 the state is not rendered to the output cell as expected (no output):
状态未按预期呈现给输出单元(无输出):
In [1]: HelloWidget("Hello World!")
Out [1]:
How can this be done? 如何才能做到这一点?
I figured this out (and feel a bit dumb). 我发现了这一点(感觉有点傻)。
The trailets.Unicode
object is a descriptor, so it has to be attached to the class object, HelloWidget
. trailets.Unicode
对象是一个描述符,因此必须将其附加到类对象HelloWidget
。 So the correct code is as follows: 因此正确的代码如下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.