select.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import justpy as jp
  2. from typing import Callable, Dict, List, Optional, Union
  3. from .choice_element import ChoiceElement
  4. class Select(ChoiceElement):
  5. def __init__(self,
  6. options: Union[List, Dict],
  7. *,
  8. value: any = None,
  9. on_change: Optional[Callable] = None,
  10. ):
  11. """Dropdown Selection Element
  12. :param options: a list ['value1', ...] or dictionary `{'value1':'label1', ...}` specifying the options
  13. :param value: the inital value
  14. :param on_change: callback to execute when selection changes
  15. """
  16. view = jp.QSelect(options=options, input=self.handle_change, temp=False)
  17. super().__init__(view, options, value=value, on_change=on_change)
  18. def value_to_view(self, value: any):
  19. matches = [o for o in self.view.options if o['value'] == value]
  20. if any(matches):
  21. return matches[0]['label']
  22. else:
  23. return value
  24. def handle_change(self, msg):
  25. msg['label'] = msg['value']['label']
  26. msg['value'] = msg['value']['value']
  27. return super().handle_change(msg)