Python turtle如何实现倒计时结束后再启动海龟赛跑逻辑
问题原因
turtle是基于事件循环的GUI库,直接用time.sleep做长等待会阻塞整个界面的刷新和事件响应,这也是你之前试sleep方案没效果的核心原因- 你原代码的
countdown函数第一行写了if countdown() < 3:,这行是无参数递归调用自己,会直接触发无限递归报错,完全没执行预期的计时逻辑 - 原代码克隆海龟后颜色赋值写反了,把第一个红海龟改成了蓝色,第二个克隆的海龟没设颜色
- 赛跑函数的终点判断逻辑写反了,用
or会导致只要有一只没到终点就一直跑,永远停不下来
修复后完整代码
from turtle import Screen, Turtle from random import choice import time FONT = ('Arial', 36, 'bold') def race(): # 两只海龟都没到终点时才继续跑 while turtle_1.xcor() < 200 and turtle_2.xcor() < 200: choice([turtle_1, turtle_2]).forward(10) screen.update() time.sleep(0.01) # 加毫秒级短延时控制赛跑速度,不会阻塞事件循环 def countdown(seconds=3): pen.clear() # 每次更新数字前清空上一次的绘制内容 if seconds >= 1: pen.write(seconds, align='center', font=FONT) screen.update() # 用ontimer做1秒定时,不阻塞界面 screen.ontimer(lambda: countdown(seconds - 1), 1000) else: pen.write("GO!", align='center', font=FONT) screen.update() time.sleep(0.5) pen.clear() race() # 倒计时完全走完后才触发赛跑 screen = Screen() screen.tracer(0) # 关闭自动刷新减少卡顿 screen.bgcolor('green') # 绘制终点线 marker = Turtle() marker.hideturtle() marker.speed('fastest') marker.color('white') marker.width(5) marker.penup() marker.goto(200, 300) marker.pendown() marker.right(90) marker.forward(600) # 倒计时绘制画笔 pen = Turtle() pen.hideturtle() pen.penup() # 初始化两只参赛海龟 turtle_1 = Turtle() turtle_1.shape('turtle') turtle_1.color('red') turtle_1.penup() turtle_1.goto(-400, 200) turtle_2 = turtle_1.clone() turtle_2.color('blue') turtle_2.goto(-400, -200) screen.update() countdown() screen.mainloop() # 启动turtle主事件循环
注意事项
涉及turtle的秒级长等待,一律用
screen.ontimer(回调函数, 等待毫秒数)实现,它不会阻塞界面的渲染和事件响应;只有动画过程中控制帧率的毫秒级短延时,可以用time.sleep实现。
内容的提问来源于stack exchange,提问作者24bit
相关产品推荐
相关产品推荐

