瀏覽代碼

allow activating and deactivating a timer

Falko Schindler 4 年之前
父節點
當前提交
4c49010f39
共有 2 個文件被更改,包括 9 次插入3 次删除
  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():
             with ui.row():
                 ui.icon('far fa-clock')
                 ui.icon('far fa-clock')
                 clock = ui.label()
                 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'):
         with ui.card().add_classes('items-center'):
             ui.label('Style', 'h5')
             ui.label('Style', 'h5')

+ 7 - 2
nicegui/timer.py

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