如何通过Python turtle的onscreenclick实现点击后重复运行程序
修改后可循环运行的完整代码
import turtle import time from random import randint # 初始化全局窗口 wn = turtle.Screen() wn.title("Reaction test") wn.setup(width=600, height=600) wn.tracer(0) wn.bgcolor("blue") turtle.hideturtle() # 记录反应开始时间的全局变量 start_time = 0 # 初始启动页 def init_page(): wn.bgcolor("blue") turtle.clear() turtle.write("Click to start", move=False, align="center", font=("Arial", 40, "normal")) wn.onscreenclick(start_game) # 开始游戏的逻辑 def start_game(x, y): # 解绑点击事件避免重复触发 wn.onscreenclick(None) turtle.clear() wn.bgcolor("red") turtle.write(" Click when the\nscreen turns green", move=False, align="center", font=("Arial", 40, "normal")) # 用ontimer替代sleep,避免阻塞界面 wait_time = randint(2, 10) * 1000 wn.ontimer(turn_green, wait_time) # 屏幕变绿,开始计时 def turn_green(): global start_time wn.bgcolor("green") turtle.clear() turtle.write("CLICK!", move=False, align="center", font=("Arial", 40, "normal")) start_time = time.perf_counter() wn.onscreenclick(show_result) # 展示反应结果 def show_result(x, y): wn.onscreenclick(None) reaction_ms = round((time.perf_counter() - start_time) * 1000) turtle.clear() turtle.write(f"Your reaction time was\n {reaction_ms} milliseconds", move=False, align="center", font=("Arial", 40, "normal")) # 绑定点击事件,点击回到初始页实现循环 wn.onscreenclick(lambda x,y: init_page()) # 初始加载启动页 init_page() wn.mainloop()
核心修改说明
- 用
wn.ontimer()替代原代码的sleep(),避免sleep阻塞turtle的事件循环导致界面无响应 - 拆分游戏逻辑为不同状态的独立函数,通过事件绑定实现状态流转,结果展示页点击后直接调用初始页函数,实现循环重启的效果
- 修复原代码全局计时变量未正确赋值的问题,确保反应时间计算准确
- 每次绑定新的点击事件前先解绑原有事件,避免单次点击触发多个逻辑的问题
内容的提问来源于stack exchange,提问作者EVAK
相关产品推荐
相关产品推荐

