hey guys.. I wana implement a stop watch in python... The timer turns on when my program starts and continuesly shows the time spent until the end of the program.. Can someone please help me with this..??

To run the stopwatch in the background, you need to check out the Python module threading.

Member Avatar for masterofpuppets

hi here's my version of the stop watch. it is not the best one but you'll get the point. woooee's example is better though and I agree with vegaseat about the threading:

from Tkinter import *
import time

root = Tk(); root.title( "Stop Watch" ); root.geometry( "250x100+500+200" )
c = Canvas( root, width = 250, height = 100 ); c.pack()

ms, seconds, minutes, hours = 0, 0, 0, 0
on = True

def stopWatch():
    global seconds, minutes, hours, on, ms
    h = c.create_text( 95, 30, text = str( hours ) + " :", font = "Arial" )
    m = c.create_text( 120, 30, text = str( minutes ) + " :", font = "Arial" )
    s = c.create_text( 145, 30, text = str( seconds ) + " :", font = "Arial" )
    mSec = c.create_text( 165, 30, text = str( ms ), font = "Arial" )
    stopB = Button( c, text = "Stop", bd = 4, width = 10, command = stop ); stopB.place( relx = 1, x = -158, y = 55 )
    while on:
        time.sleep( 0.1 )
        ms += 1
        if ms == 10:
            ms = 0; seconds += 1
            if seconds == 60:
                seconds = 0; minutes += 1
                if minutes == 60:
                    minutes = 0; hours += 1
        c.delete( h, m, s, mSec )
        h = c.create_text( 95, 30, text = str( hours ) + " :", font = "Arial" )
        m = c.create_text( 120, 30, text = str( minutes ) + " :", font = "Arial" )
        s = c.create_text( 145, 30, text = str( seconds ) + " :", font = "Arial" )
        mSec = c.create_text( 165, 30, text = str( ms ), font = "Arial" )
        c.update()
    
def stop():
    global on
    on = False
    
stopWatch()    
mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.