Python使用Turtle实现精确计时工具

2025-05-25 15:50

本文主要是介绍Python使用Turtle实现精确计时工具,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Python使用Turtle实现精确计时工具》这篇文章主要为大家详细介绍了Python如何使用Turtle实现精确计时工具,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下...

功能特点

数字显示当前计时(时:分:秒.毫秒)

支持开始/暂停计时(空格键)

支持重置计时(R键)

状态显示(正在计时/已暂停/按空格键开始计时)

清晰的操作提示

使用方法

运行程序后,会显示初始时间(00:00:00.000)

按下空格键开始计时

再次按下空格键暂停计时

按下R键可以重置计时器回到00:00:00.000

程序架构设计

1.核心模块:

turtle: 提供跨平台的图形化界面绘制功能

time: 提供高精度的系统时间获取功能

2.设计模式:

采用事件驱动编程模型,通过键盘事件触发状态变更

利用全局状态管理计时器状态

3.算法原理:

时间计算:利用系统时间差值计算经过时间

状态管理:使用布尔变量控制计时器运行状态

代码详解

窗口和画笔创建

import turtle
import time

# 设置窗口和基本参数
screen = turtle.Screen()
screen.title("简易计时器/秒表")
screen.bgcolor("black")
screen.setup(width=500, height=300)
screen.tracer(0)  # 关闭自动刷新

# 创建显示时间的画笔
time_display = turtle.Turtle()
time_display.hideturtle() # 隐藏turtle的箭头图标,使绘图时只显示图形而不显示箭头
time_display.color("cyan") # 设置turtle绘图的颜色
time_display.penup()   #抬起turtle的笔,这样移动turtle时不会绘制线条
time_display.goto(0, 30)  # 将turtle移动到坐标(0, 30)的位置,准备从该点开始绘图或显示文本

# 创建状态显示的画笔
status_display = turtle.Turtle()
status_display.hideturtle()
status_display.speed(0)
status_display.color("white")
status_display.penup()
status_display.goto(0, -30)

# 创建操作提示的画笔
help_display = turtle.Turtle()
help_display.hideturtle()
help_display.speed(0)
help_display.co编程lor("yellow")
help_display.penup()
help_display.goto(0, -80)
help_display.write("空格键: 开始/暂停 | R键: 重置", align="center", font=("Arial", 14, "normal"))

# 初始化秒表变量
is_running = False
start_time = 0
accumulated_time = 0

应用知识点:

  • Turtle图形对象: 创建多个Turtle对象分别负责不同UI元素的显示
  • 窗口控制: 使用screen.tracer(0)关闭自动刷新以提高性能
  • 坐标系统: 使用二维坐标系统合理布局界面元素
  • 全局状态变量: 使用全局变量跟踪计时器状态

时间和状态显示更新

# 更新时间显示
def update_time_display(elapsed_time):
    hours = int(elapsed_time / 3600)
    minutes = int((elapsed_time % 3600) / 60)
    seconds = int(elapsed_time % 60)
    milliseconds = int((elapsed_time * 1000) % 1000)
    
    time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}.{milliseconds:03d}"
    time_display.clear()
    time_display.write(time_str, align="center", font=("Arial", 40, "bold"))

# 更新状态显示
def update_status():
    status_display.clear()
    if is_running:
        status = "正在计时..."
    else:
        if accumulated_time > 0:
            status = "已暂停"
        else:
            status = "按空格键开始计时"
    status_display.write(status, align="center", font=("Arial", 20, "normal"))

应用知识点:

  • 时间单位转换: 将秒数转换为时、分、秒、毫秒
  • 取余与整除运算: 使用整除和取余操作进行时间单位分解
  • 字符串格式化: 使用f-string和格式说明符控制显示格式
  • 状态条件判断: 根据多种状态组合提供不同的用户反馈

计时器控制逻辑

def toggle_timer():
    global is_running, start_time, accumulated_time
    
    if is_running:
        # 暂停计时
        is_running = False
        accumulated_time += time.time() - start_time
    else:
        # 开始计时
        is_running = True
        start_time = time.time()
    
    update_status()

应用知识点:

  • 全局变量修改: 使用global关键字在函数内修改全局状态
  • 高精度时间获取: 使用time.time()获取高精度Unix时间戳
  • 状态切换设计: 实现简洁的状态切换逻辑

计时器重置功能

def reset_timer():
    global is_running, start_time, accumulated_time
    is_running = False
    accumulated_time = 0
    start_time = 0
    update_status()
    update_time_display(0)

应用知识点:

  • 状态重置: 将所有计时相关变量重置为初始值
  • 函数复用: 复用更新显示的函数,避免代码冗余

事件监听设置

# 设置键盘事件
screen.listen()
screen.onkeypress(toggle_timer, "space")  # 空格键开始/暂停
screen.onkeypress(reset_timer, "r")       # R键重置

应用知识点:

  • 事件监听机制: 使用listen()方法启用事件监听
  • 回调函数绑定: 将键盘事件与特定函数绑定
  • 函数引用传递: 将函数名作为参数传递,不带括号

主循环及运行控制

def main():
    # 初始显示
    update_status()
    update_time_display(0)
    
    while True:
        if is_running:
            elapsed_time = accumulated_time + (time.time() - start_time)
        else:
            elapsed_time = accumulated_time
        
        update_time_display(elapsed_time)
        screen.update()
        time.sleep(0.01)  # 小延迟减轻CPU负担

​​​​​​​# 启动程序
if __name__ == "__main__":
    try:
        main()
    except:
        print("程序已退出")
    turtle.done() 

应用知识点:

  • 无限循环: 使用while True创建游戏主循环
  • 条件计时: 根据运行状态计算不同的时间值
  • 手动屏幕刷新: 使用screen.update()手动刷新画面
  • 定时延迟: 使用time.sleep()控制循环速率,减轻CPU负担
  • 异常处理: 使用try-except捕获可能的异常,确保程序优雅退出
  • 入口点检查: 使用if __name__ == "__main__":确保直接运行时才执行主函数

完整代码

import turtle
import time

# 设置窗口和基本参数
screen = turtle.Screen()
screen.title("简易计时器/秒表")
screen.bgcolor("black")
screen.setup(width=500, height=300)
screen.tracer(0)  # 关闭自动刷新

# 创建显示时间的画笔
time_display = turtle.Turtle()
time_display.hideturtle() # 隐藏turtle的箭头图标,使绘图时只显示图形而不显示箭头
time_display.color("cyan") # 设置turtle绘图的颜色
time_display.penup()   #抬起tandroidurtle的笔,这样移动turtle时不会绘制线条
time_display.goto(0, 30)  # 将turtle移动到坐标(0, 30)的位置,准备从该点开始绘图或显示文本

# 创建状态显示的画笔
status_display = turtle.Turtle()
status_display.hideturtle()
status_display.speed(0)
status_display.color("white")
status_display.penup()
status_display.goto(0, -30)

# 创建操作提示的画笔
help_display = turtle.Turtle()
help_display.hideturtle()
help_display.speed(0)
help_display.color("yellow")
help_display.penup()
help_display.goto(0, -80)
help_display.write("空格键: 开始/暂停 | R键: 重置", align="center", font=("Arial", 14, "normal"))

# 初始化秒表变量
is_running = False
start_time = 0
accumulated_time = 0


# 更新时间显示
def update_time_display(elapsed_time):
    hours = int(elapsed_time / 3600)
    minutes = int((elapsed_time % 3600) / 60)
    seconds = int(elapsed_time % 60)
    milliseconds = int((elapsed_time * 1000) % 1000)

    time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}.{milliseconds:03d}"
    time_display.clear()
    time_display.write(time_str, align="center", font=("Arial", 40, "bold"))


# 更新状态显示
def update_status():
    status_display.clear()
    if is_running:
        status = "正在计时..."
    else:
        if accumulated_time > 0:
            status = "已暂停"
        else:
            status = "按空格键开始计时"
    status_display.write(status, align="center", font=("Arial", 20, "normal"))


def toggle_timer():
    global is_running, start_time, accumulated_time

    if is_running:
        # 暂停计时
        is_running = False
        accumulated_time += time.time() - start_time
    else:
        # 开始计时
        is_running = True
        start_time = time.time()

    update_status()

def reset_timer():
    global is_running, start_time, accumulated_time
    is_running = False
    accumulated_time = 0
    start_time = 0
    update_status()
    update_time_display(0)
# 设置键盘事件
screen.listen()
screen.onkeypress(toggle_timer, "space")  # 空格键开始/暂停
screen.onkeypress(reset_timer, "r")       # R键重置


def main():
    # 初始显示
    update_status()
    update_time_display(0)

    while True:
        if is_running:
            elapsed_time = accumulated_time + (time.time() - start_time)www.chinasem.cn
        else:
            elapsed_time = accumulated_time

        update_time_display(elapsed_time)
        screen.update()
        time.sleep(0.0DVsBah1)  # 小延迟减轻CPU负担


# 启动程序
if __name__ == "__main__":
    try:
        main()
    except:
        print("程序已退出")
    turtle.done() 

效果:

Python使用Turtle实现精确计时工具

到此这篇关于python使用China编程Turtle实现精确计时工具的文章就介绍到这了,更多相关Python计时内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Python使用Turtle实现精确计时工具的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154769

相关文章

SpringBoot实现多环境配置文件切换

《SpringBoot实现多环境配置文件切换》这篇文章主要为大家详细介绍了如何使用SpringBoot实现多环境配置文件切换功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 示例代码结构2. pom文件3. application文件4. application-dev文

Python FastAPI实现JWT校验的完整指南

《PythonFastAPI实现JWT校验的完整指南》在现代Web开发中,构建安全的API接口是开发者必须面对的核心挑战之一,本文将深入探讨如何基于FastAPI实现JWT(JSONWebToken... 目录一、JWT认证的核心原理二、项目初始化与环境配置三、安全密码处理机制四、JWT令牌的生成与验证五、

go rate 原生标准限速库的使用

《gorate原生标准限速库的使用》本文主要介绍了Go标准库golang.org/x/time/rate实现限流,采用令牌桶算法控制请求速率,提供Allow/Reserve/Wait方法,具有一定... 目录介绍安装API介绍rate.NewLimiter:创建限流器limiter.Allow():请求是否

Linux给磁盘扩容(LVM方式)的方法实现

《Linux给磁盘扩容(LVM方式)的方法实现》本文主要介绍了Linux给磁盘扩容(LVM方式)的方法实现,涵盖PV/VG/LV概念及操作步骤,具有一定的参考价值,感兴趣的可以了解一下... 目录1 概念2 实战2.1 相关基础命令2.2 开始给LVM扩容2.3 总结最近测试性能,在本地打数据时,发现磁盘空

Golang实现Redis分布式锁(Lua脚本+可重入+自动续期)

《Golang实现Redis分布式锁(Lua脚本+可重入+自动续期)》本文主要介绍了Golang分布式锁实现,采用Redis+Lua脚本确保原子性,持可重入和自动续期,用于防止超卖及重复下单,具有一定... 目录1 概念应用场景分布式锁必备特性2 思路分析宕机与过期防止误删keyLua保证原子性可重入锁自动

golang 对象池sync.Pool的实现

《golang对象池sync.Pool的实现》:本文主要介绍golang对象池sync.Pool的实现,用于缓存和复用临时对象,以减少内存分配和垃圾回收的压力,下面就来介绍一下,感兴趣的可以了解... 目录sync.Pool的用法原理sync.Pool 的使用示例sync.Pool 的使用场景注意sync.

Swagger2与Springdoc集成与使用详解

《Swagger2与Springdoc集成与使用详解》:本文主要介绍Swagger2与Springdoc集成与使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录1. 依赖配置2. 基础配置2.1 启用 Springdoc2.2 自定义 OpenAPI 信息3.

IDEA实现回退提交的git代码(四种常见场景)

《IDEA实现回退提交的git代码(四种常见场景)》:本文主要介绍IDEA实现回退提交的git代码(四种常见场景),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.已提交commit,还未push到远端(Undo Commit)2.已提交commit并push到

Kotlin Compose Button 实现长按监听并实现动画效果(完整代码)

《KotlinComposeButton实现长按监听并实现动画效果(完整代码)》想要实现长按按钮开始录音,松开发送的功能,因此为了实现这些功能就需要自己写一个Button来解决问题,下面小编给大... 目录Button 实现原理1. Surface 的作用(关键)2. InteractionSource3.

java对接第三方接口的三种实现方式

《java对接第三方接口的三种实现方式》:本文主要介绍java对接第三方接口的三种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录HttpURLConnection调用方法CloseableHttpClient调用RestTemplate调用总结在日常工作