七段数码管
基本思路
步骤1绘制单个数字对应的数码管
步骤2获得一串数字,绘制对应的数码管
步骤3获得当前系统时间,绘制对应的数码管
代码实例
import turtle
def drawLine(draw): #绘制单挑线
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
turtle.right(90)
def drawDight(dight): #绘制7条线,dight是数字取值范围是0-9
drawLine(True) if dight in [2, 3, 4, 5, 6, 8, 9] else drawLine(False) #列表范围
drawLine(True) if dight in [0, 1, 3, 4, 5, 6, 7, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 3, 5, 6, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 6, 8] else drawLine(False)
turtle.left(90)
drawLine(True) if dight in [0, 4, 5, 6, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 3, 5, 6, 7, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 1, 2, 3, 4, 7, 8, 9] else drawLine(False)
turtle.left(180)
turtle.penup() #为绘制后续数字确定位置
turtle.fd(20) #为后续数字确定位置
def drawDate(date):#可能是时间的字符串
for i in date:
drawDight(eval(i))#通过eval()函数将数字变为整数
def main():#定义主函数,绘制数字,定义画笔,前进步数,主要用来设定初始值
turtle.setup(800, 350, 200, 200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
drawDate('1214')
turtle.hideturtle()
turtle.done()
main()
代码优化
通过增加像素,修改绘制七段数码管,显示当前时间。
1、使用time库获得系统是当前时间
2、增加年月日标记
3、年月日颜色不同
扩展年月日标记
import turtle,time
def drawLine(draw): #绘制单挑线
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
turtle.right(90)
def drawDight(dight): #绘制7条线,dight是数字取值范围是0-9
drawLine(True) if dight in [2, 3, 4, 5, 6, 8, 9] else drawLine(False) #列表范围
drawLine(True) if dight in [0, 1, 3, 4, 5, 6, 7, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 3, 5, 6, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 6, 8] else drawLine(False)
turtle.left(90)
drawLine(True) if dight in [0, 4, 5, 6, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 2, 3, 5, 6, 7, 8, 9] else drawLine(False)
drawLine(True) if dight in [0, 1, 2, 3, 4, 7, 8, 9] else drawLine(False)
turtle.left(180)
turtle.penup() #为绘制后续数字确定位置
turtle.fd(20) #为后续数字确定位置
def drawDate(date):#可能是时间的字符串,date为日期,格式为‘%Y-%m=%d+’
turtle.pencolor("red")#定义画笔颜色,字号
for i in date:
if i == '-':
turtle.write('年',font=("Arial", 18, "normal" ))
turtle.pencolor("green")
turtle.fd(40)
elif i == '=':
turtle.write('月', font=("Arial", 18,"normal"))
turtle.pencolor("blue")
turtle.fd(40)
elif i == '+':
turtle.write('日', font=("Arial", 18,"normal"))
else:
drawDight(eval(i))
def main():#定义主函数,绘制数字,定义画笔,前进步数,主要用来设定初始值
turtle.setup(800, 350, 200, 200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))#使用了当前时间
turtle.hideturtle()
turtle.done()
main()
举一反三
方法思维
模块化思维:确定模块接口,封装功能
规则化思维:抽象过程为规则,计算机自动执行
华繁琐为简单:将大功能化小工程
问题扩展,绘制带小数点的七段数码管,刷新的时间倒计时效果