Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Stopwatch with new ui module, is there a better solution than `threading`?
-
As part of a larger project using the awesome new ui module, I'd like to make a stopwatch. I have a label displaying the time, and a button to reset the counter. I'm using the threading module to update the time in the background while waiting for taps. It works, but it seems like there is probably a cleaner way to do things. Any suggestions?
import ui from time import time,sleep,strftime,gmtime import threading t = time() def reset_button(sender): '@type sender: ui.Button' global t t = time() class update_time(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: sleep(1) v['display_timer'].text = strftime('%H:%M:%S', gmtime(time()-t)) v = ui.load_view('ragnar') background = update_time() background.start() v.present(orientations=['portrait'])
-
You could use the
ui.delay
function for this. -
Thanks! It looks like @ui.in_background does the trick too.
import ui from time import time,sleep,strftime,localtime,gmtime t = time() def reset_button(sender): '@type sender: ui.Button' global t t = time() @ui.in_background def update_time(): while True: sleep(1) v['countdown_timer'].text = strftime('%H:%M:%S', gmtime(time()-t)) v = ui.load_view('ragnar') update_time() v.present(orientations=['portrait'])