比方說,我想要一個由IntText小部件和DropDown小部件組成的小部件,該小部件的值是這些小部件值的連接字符串。我能怎麼做?如何從多個創建ipywidgets?
下面是一個嘗試:
import re
import ipywidgets as ipw
from IPython.display import display
class IntMultipliedDropdown:
_VALUE_PATTERN = re.compile('(?P<num>\d+) (?P<option>\w+-?\w*)')
def __init__(self, options, option_value, int_value=1):
self.number = ipw.IntText(int_value)
self.options = ipw.Dropdown(options=options, value=option_value)
self.box = ipw.HBox([self.number, self.options])
self.number.observe(self._on_changes, names='value')
self.options.observe(self._on_changes, names='value')
self._handelers = []
def _on_changes(self, change):
for handeler in self._handelers:
handeler(self.value)
@property
def value(self):
return "{} {}".format(self.number.value, self.options.value)
@value.setter
def value(self, value):
match = re.search(self._VALUE_PATTERN, value)
groupdict = match.groupdict()
self.number.value = groupdict['num']
self.options.value = groupdict['option']
def _ipython_display_(self, **kwargs):
return self.box._ipython_display_(**kwargs)
def observe(self, handler):
if handler not in self._handelers:
self._handelers.append(handler)
mywidget = IntMultipliedDropdown(['apple', 'bed', 'cell'], 'cell')
mywidget.observe(print)
display(mywidget)
print('default value:', mywidget.value)
mywidget.value = '2 bed'
它的工作原理,但也有缺點。首先,當我設置mywidget.value
時,觀察到的功能被調用兩次:關於數值變化和選項值變化。
第二,最糟糕的是,我不能在一個盒子插件一樣使用此插件:
ipw.HBox([ipw.Label('Mylabel'), mywidget])
這就提出:
ValueError: Can't clean for JSON: <__main__.IntMultipliedDropdown object at 0x7f7d604fff28>
有沒有更好的解決辦法?