Turtle模块绝对是吸引非专业代码开发者学习Python入门的好工具,通过turtle几行代码的执行软件就会画出漂亮的图形,美观而且有成就感。这些漂亮的图形如三角形、五角星、机器猫等。在写代码的时候改变几个参数,就可以产生新的奇怪形状。
那今天我们看看如何用Python语言里turtle模块编写动态万年历吧!
操作步骤如下:
首先:
import turtle
import datetime,time
注意: 定义画线or不画线函数
t=turtle.Turtle()
t.speed(1)
注意:速度慢
t.screen.delay(0)
t._tracer(False)
注意:不显示绘图过程
l = 20,要标注:线的长度
def DrawLine(draw):
global l
if draw:
t.forward(l)
else:
t.penup()
t.forward(l)
t.pendown()
定义绘制函数,数码管的7笔画
def DrawDigit(digit):
DrawLine(True) if digit in (2, 3, 4, 5, 6, 8, 9) else DrawLine(False)
t.right(90)
DrawLine(True) if digit in (0, 1, 3, 4,5, 6, 7, 8, 9) else DrawLine(False)
t.right(90)
DrawLine(True) if digit in (0, 2, 3, 5, 6, 8, 9) else DrawLine(False)
t.right(90)
DrawLine(True) if digit in (0, 2, 6, 8) else DrawLine(False)
DrawLine(True) if digit in (0, 4,5, 6, 8, 9) else DrawLine(False)
t.right(90)
DrawLine(True) if digit in (0, 2, 3, 5, 6, 7, 8, 9) else DrawLine(False)
t.right(90)
DrawLine(True) if digit in (0, 1, 2, 3, 4, 7, 8, 9) else DrawLine(False)
t.right(90)
t.penup()
t.right(180)
t.fd(20)
t.pendown()
汉字的输出函数,操作如下:
def write_data(s):
global l
t.right(90)
t.penup()
t.forward(l)
t.pencolor((1,0,0))
t.write(s, font=("C:\\windows:\\font:\\msyh.ttl", "30"))
t.forward(-l)
t.left(90)
t.forward(2*l)
t.pd()
t.color((0, 0, 0))
定义绘制函数,操作如下:
def Draw(data):
x=data.split(“ “)
s=[“年”,”月”,”日”,”时”,”分”,”秒”]
for I in range(0,6):
for digit in x[i]:
digit = int(digit)
DrawDigit(digit)
write_data(s[i])
定义主函数,操作如下:
def main():
t.reset()
t.penup()
t.forward(-400)
t.pendown()
获取时间数据,引入时间"%Y %m %d %H %M %S"
Draw(datetime.datetime.now().strftime("%Y %m %d %H %M %S"))
调用主函数
while True:
main()
注意:t.screen.mainloop()
time.sleep(1)
结果显示: