实例:运用编写函数打印当前日期和时间
1.导入库模块
from turtle import * #用这种方式导入,方法前面不能添加库名turtle
from random import * #导入随机库模块
import time
2.绘制单段管间隔
def drawGap():
penup()
fd(5)
3.绘制单段数码管
def drawLine(draw):
drawGap()
if draw:
pendown()
else:
penup()
fd(20)
drawGap()
right(90)
4.根据数字绘制七段数码管
def drawDigit(digit):
#第1段
pencolor(random(),random(),random())
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False) #用条件表达式判断
#第2段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
#第3段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,3,5,6,8] else drawLine(False)
#第4段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,6,8] else drawLine(False)
left(90)
#第5段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
#第6段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
#第7段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
left(180)
penup()
fd(20) #数字之间的间隙为20像素
5.获得要输出的数字
def drawData(date):
for i in date:
if i=='-':
write('年',font=('黑体',20,'normal'))
elif i=='=':
write('月',font=('黑体',20,'normal'))
fd(40)
elif i=='+':
write('日',font=('黑体',20,'normal'))
else:
drawDigit(eval(i)) #调用画数字函数
6.主函数(设置画布与画笔等)
def main():
setup(850,350) #设置画布的大小
bgcolor('black') #画布背景颜色
penup()
fd(-300) #向左行进像素
pendown()
pensize(5)
speed(20) #画笔速度
#date=input('请输入您的生日:')
date=time.strftime('%Y-%m=%d+')
drawData(date)
hideturtle() #隐藏画笔
done() #结束程序
7.调用主函数
main()