用Python中的turtle 绘图,绘制表示年、月、日、时、分、秒的七段数码管
时间: 2023-05-31 16:01:35 浏览: 83
Python绘制七段数码管实例代码
5星 · 资源好评率100%
以下是绘制七段数码管的Python代码:
```python
import turtle
# 定义每个数码管的绘制函数
def draw_segment(x, y, width, height):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.setheading(0)
turtle.forward(width)
turtle.setheading(90)
turtle.forward(height)
turtle.setheading(180)
turtle.forward(width)
turtle.setheading(270)
turtle.forward(height)
turtle.penup()
# 定义每个数字的七段数码管布局
digit_layout = {
0: [(0, 0), (0, 40), (40, 0), (40, 40), (0, -40), (40, -40)],
1: [(20, 0), (20, 40), (20, -40)],
2: [(0, 0), (40, 0), (40, 20), (0, -20), (0, -40), (40, -40)],
3: [(0, 0), (40, 0), (40, 40), (0, -20), (40, -20)],
4: [(0, 0), (0, 20), (40, 20), (40, 0), (40, -40)],
5: [(0, 0), (40, 0), (40, -20), (0, 20), (0, -40), (40, -40)],
6: [(0, 0), (0, 20), (40, 20), (40, 0), (0, -40), (40, -40)],
7: [(0, 0), (40, 0), (20, 40), (20, -40)],
8: [(0, 0), (0, 20), (40, 20), (40, 0), (0, -20), (40, -20), (0, -40), (40, -40)],
9: [(0, 0), (40, 0), (40, 20), (0, 20), (0, -20), (40, -20), (40, -40)]
}
# 绘制整个七段数码管
def draw_digit(x, y, digit):
turtle.color('red')
for segment in digit_layout[digit]:
draw_segment(x + segment[0], y + segment[1], 20, 20)
# 绘制年月日时分秒
def draw_datetime(year, month, day, hour, minute, second):
turtle.tracer(False)
turtle.clear()
turtle.penup()
turtle.goto(-200, 0)
draw_digit(0, 0, year // 1000)
draw_digit(50, 0, (year // 100) % 10)
draw_digit(100, 0, (year // 10) % 10)
draw_digit(150, 0, year % 10)
draw_segment(200, 20, 20, 20)
draw_segment(200, -20, 20, 20)
draw_digit(250, 0, month // 10)
draw_digit(300, 0, month % 10)
draw_segment(350, 20, 20, 20)
draw_segment(350, -20, 20, 20)
draw_digit(400, 0, day // 10)
draw_digit(450, 0, day % 10)
draw_segment(500, 20, 20, 20)
draw_segment(500, -20, 20, 20)
draw_digit(550, 0, hour // 10)
draw_digit(600, 0, hour % 10)
draw_segment(650, 20, 20, 20)
draw_segment(650, -20, 20, 20)
draw_digit(700, 0, minute // 10)
draw_digit(750, 0, minute % 10)
draw_segment(800, 20, 20, 20)
draw_segment(800, -20, 20, 20)
draw_digit(850, 0, second // 10)
draw_digit(900, 0, second % 10)
turtle.tracer(True)
# 使用当前系统时间绘制七段数码管
import time
while True:
now = time.localtime()
draw_datetime(now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec)
time.sleep(1)
```
运行后,会不断更新屏幕上显示的七段数码管,以显示当前的时间。其中 `draw_datetime()` 函数接受年、月、日、时、分、秒六个参数,分别表示当前时间的各个部分。使用 `time.localtime()` 函数获取当前系统时间,并传递给 `draw_datetime()` 函数进行绘制。
阅读全文