0

I was wondering how you can print the time (in seconds) in a graphics window. I am trying to make a stop watch, and I have the stop watch png displayed in a window, but how can I show the time in the window in a specific area?
Also, is there a way to format the time like a real stop watch (hh:mm:ss) where after 60 seconds it adds 1 minute?

from graphics import *
import time

def main():
    win = GraphWin('Stopwatch', 600, 600)
    win.yUp()

    #Assigning images
    stopWatchImage = Image(Point (300, 300), "stopwatch.png")
    startImage = Image(Point (210, 170), "startbutton.png")
    stopImage = Image(Point (390, 170), "stopbutton.png")
    lapImage = Image(Point (300, 110), "lapbutton.png")

    #Drawing images
    stopWatchImage.draw(win)
    startImage.draw(win)
    stopImage.draw(win)
    lapImage.draw(win)

main()
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sammy
  • 51
  • 2
  • 11

1 Answers1

0

If it were possible, you could try the following but you'll notice this error upon running...

RuntimeError: main thread is not in main loop

(Zelle Graphics is just a wrapper around Tkinter)

Comment out all the graphics stuff, and you'll see the print statements increment every second.

from graphics import *
import datetime
from threading import Thread
import time

class StopWatch:
    def __init__(self):
        self.timestamp = datetime.time(hour = 0, minute = 0, second = 0)

    def __str__(self):
        return datetime.time.strftime(self.timestamp, '%H:%M:%S')

    def increment(self, hours=0, minutes=0, seconds=1):
        dummy_date = datetime.date(1, 1, 1)
        full_datetime = datetime.datetime.combine(dummy_date, self.timestamp)
        full_datetime += datetime.timedelta(seconds=seconds, hours=hours, minutes=minutes)
        self.timestamp = full_datetime.time()


def main():
    win = GraphWin('Stopwatch', 600, 600)
    watch = StopWatch()

    timer_text = Text(Point(200, 200), str(watch))
    timer_text.draw(win)

    def updateWatch():
        while True:
            time.sleep(1)
            watch.increment()
            print(str(watch))
            timer_text.setText(str(watch))

    t1 = Thread(target=updateWatch)
    t1.setDaemon(True)
    t1.start()
    t1.join()

    win.getMouse()


if __name__ == "__main__":
    main()
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245