main.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. import random
  3. from nicegui import ui
  4. from nicegui.binding import BindableProperty, bind_from
  5. class colorful_label(ui.label):
  6. """A label with a bindable background color."""
  7. # this class variable defines what happens when the background property changes
  8. background = BindableProperty(on_change=lambda sender, bg: sender.on_background_change(bg))
  9. def __init__(self, text: str):
  10. super().__init__(text)
  11. self.background = None # initialize the background property
  12. def on_background_change(self, bg: str) -> None:
  13. """Update the classes of the label when the background property changes."""
  14. self._classes = [c for c in self._classes if not c.startswith('bg-')]
  15. self._classes.append(bg)
  16. self.update()
  17. def shuffle():
  18. for key in data:
  19. data[key] = random.choice([True, False])
  20. ui.button('shuffle', on_click=shuffle)
  21. data = {}
  22. for k in 'abcde':
  23. data[k] = random.choice([True, False])
  24. label = colorful_label(k.upper()).classes('w-48 text-center')
  25. # binding from the data to the label
  26. # there is also a bind_to method which would propagate changes from the label to the data
  27. # and a bind method which would propagate changes both ways
  28. bind_from(label, 'background', data, k, backward=lambda x: 'bg-green' if x else 'bg-red')
  29. ui.run()