Tkinter and a clock

Matthew Dixon Cowles matt at mondoinfo.com
Mon Sep 3 15:36:44 EDT 2001


On 2 Sep 2001 21:51:25 -0700, rob shugg <shuggy at volcanomail.com>
wrote:

>I have an application where I need to display a clock during a data
>acquisition operation. The clock needs to display seconds and I need
>to be able to start stop and reset it like a stopwatch. I have been
>reading about threading issues with Tkinter and am wondering what
>aproach to take. Can someone give me some pointers?

Dear Rob,
The easiest thing would be to use Tkinter's alarm-style event. I'll
append a simple example of how it might be done. There aren't any
guarantees about when your code will be called but then there aren't
any guarantees about when a thread will be executed either.

Fredrik Lundh's excellent An Introduction to Tkinter provides good
documentation for it. It's at:

http://www.pythonware.com/library/tkinter/introduction/index.htm

Indeed, the whole document is very valuable to anyone doing Tkinter
programming. I've long since saved a copy locally to save Fredrik the
bandwidth.

Regards,
Matt



#!/usr/local/bin/python

import time
from Tkinter import *

class mainWin:

  def __init__(self,root):
    self.root=root
    self.createWidgets()
    self.clockStartedAt=None
    self.timeAccumulated=None
    self.afterID=None
    return None

  def createWidgets(self):
    b=Button(self.root,text="Start",command=self.startClock)
    b.pack()
    b=Button(self.root,text="Stop",command=self.stopClock)
    b.pack()
    b=Button(self.root,text="Reset",command=self.resetClock)
    b.pack()
    self.clockDisplay=Label(self.root,width=20,borderwidth=2,relief=GROOVE)
    self.clockDisplay.pack()
    return None

  def startClock(self):
    self.clockStartedAt=time.time()
    self.afterID=self.root.after(200,self.updateClock)
    return None

  def updateClock(self):
    val=time.time()-self.clockStartedAt
    if self.timeAccumulated<>None:
      val=val+self.timeAccumulated
    self.clockDisplay.configure(text=str(int(val)))
    self.afterID=self.root.after(200,self.updateClock)
    return None

  def stopClock(self):
    self.timeAccumulated=time.time()-self.clockStartedAt
    self.clockStartedAt=None
    if self.afterID<>None:
      self.root.after_cancel(self.afterID)
    self.afterID=None
    return None

  def resetClock(self):
    self.clockStartedAt=None
    self.timeAccumulated=None
    self.clockDisplay.configure(text="")
    return None

def main():
  root=Tk()
  mainWin(root)
  root.mainloop()
  return None

if __name__=='__main__':
  main()




More information about the Python-list mailing list