Search code examples
pythonturtle-graphicspython-datetimepython-turtle

Is there a more efficient way of looping a countdown timer using the turtle module?


Hey I'm trying to make a simple countdown timer that counts down until my exams. It technically works but the way I've coded the "days" number being written is really inefficient. I had to do it this way though because when I had two texts being written (see code snippet below), the latter one would always blink.

text.write(str(delta), align="center", font=("Arial", 50, "normal"))
text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))

Here's the full code:

from turtle import Screen, Pen, Turtle
import datetime as dt

wn = Screen()
wn.title("Countdown until Mock Exams")
wn.tracer(0)
wn.colormode(255)
# wn.setup(width=300, height=200)

text = Turtle()
text.ht()
text2 = Turtle()
text2.ht()
text2.goto(0, -55)
zzz = 0
date_exams = dt.date(2022, 2, 14)

while True:
    print(zzz)
    # text.clear()
    text2.clear()
    date_now = dt.date.today()
    # print(dt.datetime())

    delta = date_exams-date_now
    delta = str(delta).split(",")
    del delta[-1]
    delta = delta[0]

    x = dt.datetime.today().strftime("%H:%M:%S")
    y = "23:59:59"
    format = "%H:%M:%S"

    delta_time = dt.datetime.strptime(y, format) - dt.datetime.strptime(x, format)
    text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))

    if zzz == 100 or zzz == 0: # this technically works but PC has to do more work (ie. fans start blowing)
        text.clear()
        text.write(str(delta), align="center", font=("Arial", 50, "normal"))
        zzz = 0
    zzz += 1

Any help is greatly appreciated!


Solution

  • You can use time.sleep(1.0) rather than counting the zzz.

    from turtle import Screen, Pen, Turtle
    import datetime as dt
    import time
    
    wn = Screen()
    wn.title("Countdown until Mock Exams")
    wn.tracer(0)
    wn.colormode(255)
    # wn.setup(width=300, height=200)
    
    text = Turtle()
    text.ht()
    text2 = Turtle()
    text2.ht()
    text2.goto(0, -55)
    date_exams = dt.date(2022, 2, 14)
    
    while True:
        text2.clear()
        date_now = dt.date.today()
        # print(dt.datetime())
    
        delta = date_exams - date_now
        delta = str(delta).split(",")
        del delta[-1]
        delta = delta[0]
    
        x = dt.datetime.today().strftime("%H:%M:%S")
        y = "23:59:59"
        format = "%H:%M:%S"
    
        delta_time = dt.datetime.strptime(y, format) - dt.datetime.strptime(x,
                                                                            format)
        text2.write(str(delta_time), align="center", font=("Arial", 35, "normal"))
    
        text.write(str(delta), align="center", font=("Arial", 50, "normal"))
        time.sleep(1.0)