0

我想知道如何在图形窗口中打印时间(以秒为单位)。我正在尝试制作秒表,并且我在窗口中显示了秒表 png,但是如何在特定区域的窗口中显示时间?
此外,有没有办法像真正的秒表(hh:mm:ss)一样格式化时间,60秒后它增加1分钟?

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()
4

1 回答 1

0

如果可能,您可以尝试以下操作,但您会在运行时注意到此错误...

RuntimeError:主线程不在主循环中

(Zelle Graphics 只是 Tkinter 的封装)

注释掉所有图形内容,您会看到打印语句每秒都在增加。

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()
于 2016-11-08T23:44:43.047 回答