Intitext 위젯과 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>
더 나은 솔루션이 있습니까
두 번째 최악 내가 같은 상자 위젯이 위젯을 사용할 수 있다는 것입니다?