基本思路:
1.绘制单个数字对应的数码管
2.获得一串数字,绘制对应的数码管
3.获得当前系统时间,绘制对应的数码管

七段数码管对应线条:

python数码管案例 python七段数码管绘制代码_git

首先,绘制单个数字对应的数码管函数:

def drawGap():#绘制数码管间隔
    turtle.penup()
    turtle.fd(5)
def drawLine(draw): 
	drawGap()
    if (draw):
        turtle.pendown()
    else:
        turtle.penup()
    turtle.fd(40)
    turtle.right(90)

之后,根据数字绘制七段数码管:

def drawDigit(digit):#根据数字绘制七段数码管
    if digit in [2,3,4,5,6,8,9]:#1
        drawLine(True)
    else:
        drawLine(False)
    if digit in [0,1,3,4,5,6,7,8,9]:#2
        drawLine(True)
    else:
        drawLine(False)        
    if digit in [0,2,3,5,6,8,9]:#3
        drawLine(True)
    else:
        drawLine(False)
    if digit in [0,2,6,8]:#4
        drawLine(True)
    else:
        drawLine(False)

    turtle.left(90)#左转90度
    
    if digit in [0,4,5,6,8,9]:#5
        drawLine(True)
    else:
        drawLine(False)
    if digit in [0,2,3,5,6,7,8,9]:#6
        drawLine(True)
    else:
        drawLine(False)
    if digit in [0,1,2,3,4,7,8,9]:#7
        drawLine(True)
    else:
        drawLine(False)
    turtle.left(180)
    turtle.penup()#为绘制后续数字确定位置
    turtle.fd(20)#为绘制后续数字确定位置

将数字串转换成单个数字:

def drawDate(date):
    for i in date:
        drawDigit(eval(i))

定义主函数:

def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(10)
    drawDate('20200630')
    turtle.hideturtle()
    turtle.done()

程序运行结果如下:

python数码管案例 python七段数码管绘制代码_python数码管案例_02


接下来,获得当前系统时间,用于绘制对应的数码管。

修改drawDate函数:

def drawDate(date):#data为日期,格式为‘%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:
            drawDigit(eval(i))

主函数:

def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(10)
    drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))
    turtle.hideturtle()
    turtle.done()

修改后的程序结果如图:

python数码管案例 python七段数码管绘制代码_主函数_03