forked from amalkhatib90/Project01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstopwatch.py
More file actions
101 lines (69 loc) · 2.44 KB
/
stopwatch.py
File metadata and controls
101 lines (69 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import time
import tkinter as Tk
class Stopwatch:
"""
Simple stopwatch class with functionality for starting, stopping, and resetting
Attributes:
start_time: Integer to record time (0 seconds) that stopwatch was
started
formatted_time: stores a formatted time string of the current time
root: tkinter root widget - needed for timer periodic callbacks
last_after: stores last last timer callback, so that it can be cancelled
when the timer is stopped
"""
def __init__(self, root):
"""
Constructor for Stopwatch
Sets start_time variable to 0, and resets the formatted time
Args:
root: tkinter root widget, for callbacks
"""
self.start_time = 0
self.formatted_time = Tk.StringVar()
self.last_after = None
self.root = root
self.reset()
def reset(self):
"""
resets the formatted time to string of 0s
"""
self.formatted_time.set("00:00:00")
def start(self):
"""
Starts stopwatch by setting the start_time to time.time(),
rounded to the nearest whole number
Then makes a periodic callback to update the formatted time in 200 ms
"""
self.start_time = round(time.time())
def update():
"""
updates the formatted time with current time, and makes a new callback
"""
seconds = 0 if self.start_time == 0 else round(time.time() - self.start_time)
hours = seconds // 3600
seconds = seconds % 3600
minutes = seconds // 60
seconds = seconds % 60
cur_time = ""
if hours < 10:
cur_time += "0" + str(hours) + ":"
else:
cur_time += str(hours) + ":"
if minutes < 10:
cur_time += "0" + str(minutes) + ":"
else:
cur_time += str(minutes) + ":"
if seconds < 10:
cur_time += "0" + str(seconds)
else:
cur_time += str(seconds)
self.formatted_time.set(cur_time)
self.last_after = self.root.after(200, update)
update()
# Starts stopwatch
def stop(self):
"""
Stops stopwatch by removing the latest callback
"""
if self.last_after:
self.root.after_cancel(self.last_after)