本文是用python的turtle作圖的第二篇,通過這個例子可以了解動畫的原理,用python自帶的turtle庫制作一些小動畫。
1.問題描述
在上一篇“用python的turtle作圖(一)靜態圖”我們介紹了,用python自帶的turtle庫,制作靜態圖。
本文將介紹用python自帶的turtle庫制作動畫。
2.原理說明
動畫的原理簡單來說,就是利用視覺停留效應,每隔一定時間重新繪制圖形。這里有三個關鍵點:
-
擦除原來的圖形
-
重新繪制圖形
-
時間一般是二十四分之一秒之內
下面以吃豆人為例進行說明:
1、新建一個后綴是py的文件,用文本編輯器打開,導入turtle和time庫:
import turtle as t
import time
2、程序運行的時候,設置畫圖窗口大小800*600,黑色:
t.screensize(800,600,'black')
3、定義一個畫吃豆人、豆子的函數:
def draw_smile(loc):
if(loc<200):
t.color('yellow')
t.penup()
t.goto(300-loc,0)
t.dot(30,'red')
t.seth(0)
t.goto(0,-100)
t.begin_fill()
t.circle(100)
t.end_fill()
if(loc<200):
t.color('black')
t.goto(87,-51)
t.pendown()
t.seth(60)
t.begin_fill()
t.circle(100,60)
t.goto(0,0)
t.end_fill()
4)擦除原理的圖像,左移10個像素重新繪制吃豆人和豆子
for r in range(0,200,10):
t.tracer(False)
t.clear()
draw_smile(r)
time.sleep(1)
t.hideturtle()
t.tracer(True)
3.代碼實現
完整的代碼如下:
import turtle as t
import time
def draw_smile(loc):
if(loc<200):
t.color('yellow')
t.penup()
t.goto(300-loc,0)
t.dot(30,'red')
t.seth(0)
t.goto(0,-100)
t.begin_fill()
t.circle(100)
t.end_fill()
if(loc<200):
t.color('black')
t.goto(87,-51)
t.pendown()
t.seth(60)
t.begin_fill()
t.circle(100,60)
t.goto(0,0)
t.end_fill()
t.tracer(False)
t.screensize(800,600,'black')
t.color('yellow')
t.speed(1)
for r in range(0,200,10):
t.tracer(False)
t.clear()
draw_smile(r)
time.sleep(1)
t.hideturtle()
t.tracer(True)
t.clear()
t.tracer(0)
draw_smile(0)
程序運行效果如下:
3.總結
本着Talk is cheap. Show me the code
原則,代碼實現不做過多解釋。
寫起來,並不難,多試試就可以了。
本文從構思到完成,可謂是耗費了大量的心血。
如果您閱讀本文后哪怕有一丟丟收獲,請不要吝嗇你手中關注和點贊的權力,謝謝!