Jelajahi Sumber

allow activating and deactivating a timer

Falko Schindler 4 tahun lalu
induk
melakukan
4c49010f39
2 mengubah file dengan 9 tambahan dan 3 penghapusan
  1. 2 1
      examples.py
  2. 7 2
      nicegui/timer.py

+ 2 - 1
examples.py

@@ -35,7 +35,8 @@ with ui.row():
             with ui.row():
                 ui.icon('far fa-clock')
                 clock = ui.label()
-                ui.timer(0.1, lambda: clock.set_text(datetime.now().strftime("%X")))
+                t = ui.timer(0.1, lambda: clock.set_text(datetime.now().strftime("%X")))
+            ui.checkbox('active').bind_value(t.active)
 
         with ui.card().add_classes('items-center'):
             ui.label('Style', 'h5')

+ 7 - 2
nicegui/timer.py

@@ -1,6 +1,7 @@
 import asyncio
 import time
 import traceback
+from binding import BindableProperty
 from .elements.element import Element
 from .utils import handle_exceptions
 
@@ -8,9 +9,12 @@ class Timer:
 
     tasks = []
 
+    active = BindableProperty
+
     def __init__(self, interval, callback, *, once=False):
 
         parent = Element.view_stack[-1]
+        self.active = True
 
         async def timeout():
 
@@ -23,8 +27,9 @@ class Timer:
             while True:
                 try:
                     start = time.time()
-                    handle_exceptions(callback)()
-                    await parent.update()
+                    if self.active:
+                        handle_exceptions(callback)()
+                        await parent.update()
                     dt = time.time() - start
                     await asyncio.sleep(interval - dt)
                 except: