Преглед на файлове

example: custom binding

Rodja Trappe преди 1 година
родител
ревизия
d239645c03
променени са 2 файла, в които са добавени 42 реда и са изтрити 0 реда
  1. 41 0
      examples/custom_binding/main.py
  2. 1 0
      main.py

+ 41 - 0
examples/custom_binding/main.py

@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+
+import random
+
+from nicegui import ui
+from nicegui.binding import BindableProperty, bind_from
+
+
+class colorful_label(ui.label):
+    """A label with a bindable background color."""
+
+    # this class variable defines what happens when the background property changes
+    background = BindableProperty(on_change=lambda sender, bg: sender.on_background_change(bg))
+
+    def __init__(self, text: str):
+        super().__init__(text)
+        self.background = None  # initialize the background property
+
+    def on_background_change(self, bg: str) -> None:
+        """Update the classes of the label when the background property changes."""
+        self._classes = [c for c in self._classes if not c.startswith('bg-')]
+        self._classes.append(bg)
+        self.update()
+
+
+def shuffle():
+    for key in data:
+        data[key] = random.choice([True, False])
+
+
+ui.button('shuffle', on_click=shuffle)
+data = {}
+for k in 'abcde':
+    data[k] = random.choice([True, False])
+    label = colorful_label(k.upper()).classes('w-48 text-center')
+    # binding from the data to the label
+    # there is also a bind_to method which would propagate changes from the label to the data
+    # and a bind method which would propagate changes both ways
+    bind_from(label, 'background', data, k, backward=lambda x: 'bg-green' if x else 'bg-red')
+
+ui.run()

+ 1 - 0
main.py

@@ -349,6 +349,7 @@ async def index_page(client: Client) -> None:
                          '[zauberzeug/nicegui](https://hub.docker.com/r/zauberzeug/nicegui) docker image')
             example_link('Download Text as File', 'providing in-memory data like strings as file download')
             example_link('Generate PDF', 'create SVG preview and PDF download from input form elements')
+            example_link('Custom Binding', 'create a custom binding for a label with a bindable background color')
 
     with ui.row().classes('dark-box min-h-screen mt-16'):
         link_target('why')