button.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import asyncio
  2. from typing import Awaitable, Callable, Union
  3. import justpy as jp
  4. from ..binding import bind_from, bind_to, BindableProperty
  5. from ..utils import handle_exceptions, provide_arguments, async_provide_arguments
  6. from .element import Element
  7. class Button(Element):
  8. text = BindableProperty
  9. def __init__(self,
  10. text: str = '',
  11. *,
  12. on_click: Union[Callable, Awaitable] = None,
  13. ):
  14. """Button Element
  15. :param text: the label of the button
  16. :param on_click: callback which is invoked when button is pressed
  17. """
  18. view = jp.QButton(label=text, color='primary')
  19. super().__init__(view)
  20. self.text = text
  21. self.bind_text_to(self.view, 'label')
  22. if on_click is not None:
  23. if asyncio.iscoroutinefunction(on_click):
  24. view.on('click', handle_exceptions(async_provide_arguments(func=on_click, update_function=view.update)))
  25. else:
  26. view.on('click', handle_exceptions(provide_arguments(on_click)))
  27. def set_text(self, text: str):
  28. self.text = text
  29. def bind_text_to(self, target_object, target_name, forward=lambda x: x):
  30. bind_to(self, 'text', target_object, target_name, forward=forward)
  31. return self
  32. def bind_text_from(self, target_object, target_name, backward=lambda x: x):
  33. bind_from(self, 'text', target_object, target_name, backward=backward)
  34. return self
  35. def bind_text(self, target_object, target_name, forward=lambda x: x, backward=lambda x: x):
  36. bind_from(self, 'text', target_object, target_name, backward=backward)
  37. bind_to(self, 'text', target_object, target_name, forward=forward)
  38. return self