一、效果图:
二、获取时间函数
import time #引用时间库
time.time() #输出随机时间
time( ):返回从1970年1月1日到现在的秒数,返回值为浮点数
time.localtime() #输出本地时间
localtime(时间戳 ):将时间戳转化为时间元组(本地时间),时间戳默认为当前时间
time.strftime('%Y-%m-%d %H:%M:%S')
strftime(格式,时间元组):将指定的时间元组转化成相应的字符串格式,默认为当前时间
三、绘制单端数码电子管
1、将数字分为七个线条(每个数字的线条不同,用if...else判断),七个线段的绘制顺序相同
2、输入随机数字并绘制:获取数字,绘制多个数码管,需要确定每个数字的位置
3、获取系统时间并绘制
#导入库模块
from turtle import *
from random import *
import time #时间库
绘制单段间隔
def drawGap():
penup() #将画笔设置成飞行模式
fd(5) #将画笔向前行进五像素
绘制单段数码管
def drawLine(draw):
drawGap() #间隔函数
if draw:
pendown() #放下画笔,将画笔设置成画图(工作)模式
else:
penup()
fd(40) #画笔向前行进40像素
drawGap() #第二次调用间隔函数
right(90) #将画笔向右(前进向下)旋转90度
获得要输出的数字
def drawDigit(digit):
#第一段
pencolor(random(),random(),random())
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False) #用条件表达式判断
#第二段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
#drawDigit(True) if draw not in [2] else drawLine(False)
#第三段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,3,5,6,8] else drawLine(False)
#第四段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,6,8] else drawLine(False)
#第五段
left(90)
pencolor(random(),random(),random())
drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
#第六段
pencolor(random(),random(),random())
drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
#第七段
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)
获取主要输出的数字
def drawData(date):
for i in date:
#drawDigit(eval(digit)) #调用画数字函数
if i=='-':
write('年',font=("楷体",20,"normal"))
fd(40)
elif i=='=':
write('月',font=("楷体",20,"normal"))
fd(40)
elif i=='+':
write('日',font=("楷体",20,"normal"))
fd(40)
else:
drawDigit(eval(i))
主函数(设置画布画笔等)
def main():
setup(850,350) #设置画布大小
bgcolor('black') #画布背景颜色
penup() #将画笔设置成飞行模式
fd(-350) #向左行进350像素
pendown()
pensize(5)
speed(200) #画速
#date = input('请输入您的生日:')
date = time.strftime('%Y-%m=%d+')
drawData(date)
hideturtle() #隐藏画笔
done() #结束程序
直接调用主函数
if __name__ == '__main__':
main()
如此就完成了七段电子数码管输出日期的效果。
条件表达式的判断:
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
#相当于
if digit in [2,3,4,5,6,8,9]:
drawLine(True)
else:
drawLine(False)
评估函数:
eval():评估函数,把字符串当作表达式
drawDigit(eval(digit)) #调用画数字函数