2. 实现以鼠标单击控制的秒表程序,计时结果以“段码屏字体”显示,运用turtle;
时间: 2023-06-18 16:04:20 浏览: 159
Java实现的计时器【秒表】功能示例
以下是一个使用turtle库实现的以鼠标单击控制的秒表程序,计时结果以“段码屏字体”显示:
```python
import turtle
import time
# 定义全局变量
start = 0 # 开始时间
running = False # 计时器状态
# 定义画笔
pen = turtle.Turtle()
pen.hideturtle()
# 定义数字的段码字典
digit_segment = {'0': [(0, 1), (1, 0), (2, 0), (3, 1), (2, 2), (1, 2)],
'1': [(1, 0), (1, 2)],
'2': [(0, 1), (2, 1), (3, 1), (0, 2), (2, 2)],
'3': [(0, 1), (1, 0), (2, 1), (3, 1), (2, 2)],
'4': [(1, 0), (1, 1), (2, 1), (2, 2), (3, 2)],
'5': [(0, 1), (1, 0), (2, 1), (3, 1), (0, 2), (2, 2)],
'6': [(0, 1), (1, 0), (2, 0), (3, 1), (0, 2), (2, 2)],
'7': [(0, 0), (1, 0), (2, 1), (1, 2)],
'8': [(0, 1), (1, 0), (2, 0), (3, 1), (0, 2), (2, 2), (1, 1)],
'9': [(0, 1), (1, 0), (2, 1), (3, 1), (0, 2), (2, 2), (1, 1)]}
def draw_digit(digit, x, y):
"""
绘制一个数字
:param digit: 要绘制的数字
:param x: 起始x坐标
:param y: 起始y坐标
"""
pen.penup()
pen.goto(x, y)
pen.pendown()
for seg in digit_segment[digit]:
x1, y1 = seg[0], seg[1]
pen.goto(x + x1 * 10, y + y1 * 10)
pen.penup()
def draw_time(t):
"""
绘制时间
:param t: 时间
"""
# 分离出时分秒
m, s = divmod(t, 60)
h, m = divmod(m, 60)
# 绘制小时
draw_digit(str(h // 10), -100, 0)
draw_digit(str(h % 10), -60, 0)
# 绘制分钟
draw_digit(str(m // 10), -20, 0)
draw_digit(str(m % 10), 20, 0)
# 绘制秒钟
draw_digit(str(s // 10), 60, 0)
draw_digit(str(s % 10), 100, 0)
def start_timer(x, y):
"""
开始计时器
"""
global start, running
start = time.time()
running = True
def stop_timer(x, y):
"""
停止计时器
"""
global start, running
running = False
elapsed = time.time() - start
draw_time(elapsed)
# 注册鼠标单击事件
turtle.onscreenclick(start_timer, 1)
turtle.onscreenclick(stop_timer, 3)
# 循环绘制
while True:
turtle.clear()
draw_time(time.time() - start)
turtle.update()
time.sleep(0.1)
```
运行程序后,单击鼠标左键开始计时,单击右键停止计时,并将计时结果以“段码屏字体”显示在turtle窗口中。
阅读全文