You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python turtle库ontimer()函数直接执行不等待,如何修复实现定时功能?

问题根因

turtle的ontimer依赖自身的GUI事件循环调度,你原来的代码用了无限循环+time.sleep(1)的逻辑,会全程阻塞事件循环,所以即使你取消ontimer的注释也不会生效。另外代码中还存在一个小问题:初始化的t对象从未执行过绘制操作,直接调用t.undo()会触发运行时错误。

调整方案

按以下步骤修改即可:

  • 删除末尾的无限循环+time.sleep代码块
  • 取消refresh函数末尾wn.ontimer(refresh, 1000)的注释
  • 删除refresh函数中没用的t.undo()行
  • 首次手动调用一次refresh启动更新
  • 末尾添加turtle.mainloop()启动事件循环
修改后的完整代码
import turtle

heure_=int(input("Enter the time in hh format: "))
minute_=int(input("Enter the minutes in mm format: "))
seconde_=int(input("Enter the seconds in ss format: "))

#calculate time
def formt(h, m, s):
    minute, seconde = divmod(s, 60)
    heure, minute = divmod(minute+m, 60)
    heure = (heure+h)%12
    return heure, minute, seconde

heure, minute, seconde = formt(heure_, minute_, seconde_)
#function to calculate hands angles
def angle(h, m, s):
    angle_s=(360 / 60) * s
    angle_m=(360 / 60) * m + angle_s*1/60
    angle_h=(360 / 12) * h + angle_m*1/12
    return angle_h, angle_m, angle_s

#hands
def aigh(h, x=0, y=0, f=100):
    hour_t.ht()
    hour_t.goto(x,y)
    hour_t.setheading(90)
    hour_t.rt(h)
    hour_t.pendown()
    hour_t.width(10)
    hour_t.forward(f)

def aigm(m, x=0, y=0, f=150):
    min_t.ht()
    min_t.goto(x,y)
    min_t.setheading(90)
    min_t.rt(m)
    min_t.pendown()
    min_t.width(5)
    min_t.forward(f)

def aigs(s, x=0, y=0, f=170):
    sec_t.ht()
    sec_t.goto(x,y)
    sec_t.setheading(90)
    sec_t.color("red")
    sec_t.width()
    sec_t.rt(s)
    sec_t.pendown()
    sec_t.width(1)
    sec_t.forward(f)

#turtles for hands
hour_t = turtle.Turtle()
min_t = turtle.Turtle()
sec_t = turtle.Turtle()

wn = turtle.Screen()
wn.title("Clock")

wn.tracer(0)

def draw(h, m, s):
    aigh(h)
    aigm(m)
    aigs(s)
    
def refresh(h=heure, m=minute, s=seconde):
    global seconde
    hour_t.undo()
    min_t.undo()
    sec_t.undo()
    
    h_, m_, s_ = formt(h, m, s)
    
    #get the hands angles
    agl_h, agl_m, agl_s = angle(h_, m_, s_)

    #draw the hands
    draw(agl_h, agl_m, agl_s)

    wn.update()
    
    seconde +=1

    wn.ontimer(refresh, 1000)

# 首次调用启动更新
refresh()
# 启动事件循环
turtle.mainloop()

内容的提问来源于stack exchange,提问作者BiRD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:54:00