1
0

main.py 1.7 KB

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