Welcome, guest | Sign In | My Account | Store | Cart

This is a small implementation of a stopwatch widget in Tkinter. The widget displays a label with minutes:seconds:1/100-seconds. The label is updated every 50 ms, but that can easily be changed. Methods are availble for starting, stopping and resetting the stopwatch. A simple program demonstrates the widget.

Python, 68 lines
 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
from Tkinter import *
import time

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()      

    def makeWidgets(self):                         
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      
    
    def _update(self): 
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)
    
    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)                
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))
        
    def Start(self):                                                     
        """ Start the stopwatch, ignore if running. """
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        
    
    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0
    
    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)
        
        
def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    
    Button(root, text='Start', command=sw.Start).pack(side=LEFT)
    Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)
    
    root.mainloop()

if __name__ == '__main__':
    main()

According to the comments about time.clock(), I have changed them to time.time().

9 comments

Tobias Klausmann 21 years, 11 months ago  # | flag

Nearly right, but... ...using time.time() instead of time.clock() will measure real time instead of the time the program has got. Will work with Python2 only.

Jørgen Cederberg (author) 21 years, 11 months ago  # | flag

time.clock(). My motive for using time.clock() was, that it says in the documentation that time.clock() is used for timing or benchmarking algorithms (even in Python 1.5.2, which I have never used). Further, as time is only measured relatively, it does not matter what the time is, when starting and stopping the stopwatch.

Tobias Klausmann 21 years, 10 months ago  # | flag

time.clock(). Well, time.clock() returns the CPU time the process has received so far, so if it doesn't get 100% CPU time, the programs perception of time will be slower than the real time.

It is used for benchmarking so that other programs running on the machine don't influence the benchmark outcome.

Alexander Thomas Cruz 12 years, 5 months ago  # | flag

It works well.

Frederico 10 years, 6 months ago  # | flag

Thanks. Updated it a little bit to suit my needs.

Ed 9 years, 1 month ago  # | flag

I have been searching for a good stopwatch example. I can't believe that this is 12 years old and the best I have found. I have been playing with this and I am stuck trying to modify it a bit. I don't know if you still get message from comments but here it goes.

I have this implemented easily enough so that I have 4 timers. I would like to start them all at the exact same time and stop them independently. I have tried a new function option but that technically doesn't start them all at the same time. The Tkinter doesn't have an option for multiple command options.

Any idea how I could I could have multiple stopwatches and start them all at the same time?

shashikant nigam 8 years, 11 months ago  # | flag

Can you please explain lap and split in this code.

Sam Comer 8 years, 5 months ago  # | flag

How can I edit this to countdown from a given number?

tommyboy3 7 years, 10 months ago  # | flag

This is great code. I want to use it to make a pinewood derby timer for my cub scout pack. I need to connect the start/stop/reset functions to mouse clicks. I'm very new to coding. Can anyone help out? For example, can anyone simply tell me what code to insert where in the above program so that a left mouse press down (when cursor is hovering over the window) resets the stopwatch? If anyone can help me with that, I think I can figure out the rest. Excuse me for being dumb at this!