main.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import random
  3. from typing import Optional, cast
  4. from typing_extensions import Self
  5. from nicegui import ui
  6. from nicegui.binding import BindableProperty, bind_from
  7. class colorful_label(ui.label):
  8. """A label with a bindable background color."""
  9. # This class variable defines what happens when the background property changes.
  10. background = BindableProperty(
  11. on_change=lambda sender, value: cast(Self, sender)._handle_background_change(value))
  12. def __init__(self, text: str = '') -> None:
  13. super().__init__(text)
  14. self.background: Optional[str] = None # initialize the background property
  15. def _handle_background_change(self, bg_class: str) -> None:
  16. """Update the classes of the label when the background property changes."""
  17. self._classes = [c for c in self._classes if not c.startswith('bg-')]
  18. self._classes.append(bg_class)
  19. self.update()
  20. temperatures = {'Berlin': 5, 'New York': 15, 'Tokio': 25}
  21. ui.button(icon='refresh', on_click=lambda: temperatures.update({city: random.randint(0, 30) for city in temperatures}))
  22. for city in temperatures:
  23. label = colorful_label().classes('w-48 text-center') \
  24. .bind_text_from(temperatures, city, backward=lambda t, city=city: f'{city} ({t}°C)')
  25. # Bind background color from temperature.
  26. # There is also a bind_to method which would propagate changes from the label to the temperatures dictionary
  27. # and a bind method which would propagate changes both ways.
  28. bind_from(self_obj=label, self_name='background',
  29. other_obj=temperatures, other_name=city,
  30. backward=lambda t: 'bg-green' if t < 10 else 'bg-yellow' if t < 20 else 'bg-orange')
  31. ui.run()