main.py 1.6 KB

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