【问题标题】:Is there a more efficient way of looping a countdown timer using the turtle module?有没有更有效的方法来使用 turtle 模块循环倒数计时器?
【发布时间】:2022-01-09 19:31:59
【问题描述】:

嘿,我正在尝试制作一个简单的倒数计时器,它可以倒计时直到我的考试。它在技术上有效,但我编写“天”数字的方式确实效率低下。但我必须这样做,因为当我写两个文本时(参见下面的代码 sn-p),后一个总是会闪烁。

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

这是完整的代码:

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

非常感谢任何帮助!

【问题讨论】:

  • 时间模块的睡眠功能是不是不能用?

标签: python turtle-graphics python-datetime python-turtle


【解决方案1】:

您可以使用time.sleep(1.0) 而不是计算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)

【讨论】:

  • 谢谢,这似乎工作得很好!
  • 不客气。如果答案令人满意,请投票并将其标记为已接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
相关资源
最近更新 更多