使用turtle库、time库编程实现循环交替绘制当前时间和自己学号的七段数码管,即绘制七段数码管显示当前时间(时分秒),一秒后绘制七段数码管显示自己学号,不断循环
时间: 2024-03-01 20:52:27 浏览: 72
好的,我理解了你的问题。以下是使用turtle库和time库编写的程序:
```python
import turtle
import time
# 七段数码管的编码
codes = {'0': (1, 1, 1, 0, 1, 1, 1),
'1': (0, 0, 1, 0, 0, 1, 0),
'2': (1, 0, 1, 1, 1, 0, 1),
'3': (1, 0, 1, 1, 0, 1, 1),
'4': (0, 1, 1, 1, 0, 1, 0),
'5': (1, 1, 0, 1, 0, 1, 1),
'6': (1, 1, 0, 1, 1, 1, 1),
'7': (1, 0, 1, 0, 0, 1, 0),
'8': (1, 1, 1, 1, 1, 1, 1),
'9': (1, 1, 1, 1, 0, 1, 1)}
# 绘制单个数字的七段数码管
def draw_digit(digit, pen):
segments = codes[digit]
pen.pendown() if segments[0] else pen.penup()
pen.forward(50)
pen.right(90)
pen.pendown() if segments[1] else pen.penup()
pen.forward(100)
pen.right(90)
pen.pendown() if segments[2] else pen.penup()
pen.forward(100)
pen.right(90)
pen.pendown() if segments[3] else pen.penup()
pen.forward(50)
pen.right(90)
pen.pendown() if segments[4] else pen.penup()
pen.forward(100)
pen.right(90)
pen.pendown() if segments[5] else pen.penup()
pen.forward(100)
pen.right(90)
pen.pendown() if segments[6] else pen.penup()
pen.forward(50)
pen.right(180)
# 绘制当前时间的七段数码管
def draw_time(pen):
pen.pencolor('red')
t = time.localtime()
h = str(t.tm_hour).rjust(2, '0')
m = str(t.tm_min).rjust(2, '0')
s = str(t.tm_sec).rjust(2, '0')
draw_digit(h[0], pen)
pen.forward(75)
draw_digit(h[1], pen)
pen.forward(75)
pen.penup()
pen.forward(25)
pen.pendown()
draw_digit(m[0], pen)
pen.forward(75)
draw_digit(m[1], pen)
pen.forward(75)
pen.penup()
pen.forward(25)
pen.pendown()
draw_digit(s[0], pen)
pen.forward(75)
draw_digit(s[1], pen)
pen.penup()
pen.home()
# 绘制自己的学号的七段数码管
def draw_number(pen):
pen.pencolor('blue')
number = '123456789' # 这里是你的学号
for digit in number:
draw_digit(digit, pen)
pen.forward(75)
pen.penup()
pen.home()
# 主程序
wn = turtle.Screen()
wn.setup(800, 600)
wn.title('七段数码管')
pen = turtle.Turtle()
pen.speed(0)
while True:
draw_time(pen)
time.sleep(1)
pen.clear()
draw_number(pen)
time.sleep(1)
pen.clear()
wn.mainloop()
```
程序的主要思路是使用turtle库绘制七段数码管,然后使用time库获取当前时间并将时间转化为字符串,最后将字符串中的每个数字绘制出来。使用一个无限循环,每隔一秒钟就绘制一次当前时间的七段数码管和自己的学号的七段数码管。
阅读全文