海龟绘图(turtle)是一个Python内置的绘图库,也被称为“Turtle Graphics”或简称“Turtles”。它采用了一种有趣的绘图方式,模拟一只小海龟在屏幕上爬行,而小海龟爬行的路径就形成了绘制的图形。这种绘图方式最初源自20世纪60年代的Logo编程语言,后来一些Python程序员构建了turtle库,使得其他程序员可以通过简单的import turtle命令,在Python中使用海龟作图。
今天就来简单举几个例子!
一,小猪佩奇
from turtle import *def nose(x, y): # 鼻子penup() # 提起笔goto(x, y) # 定位pendown() # 落笔,开始画setheading(-30) # 将乌龟的方向设置为to_angle/为数字(0-东、90-北、180-西、270-南)begin_fill() # 准备开始填充图形a = 0.4for i in range(120):if 0 <= i < 30 or 60 <= i < 90:a = a + 0.08left(3) # 向左转3度forward(a) # 向前走a的步长else:a = a - 0.08left(3)forward(a)end_fill() # 填充完成penup()setheading(90)forward(25)setheading(0)forward(10)pendown()pencolor(255, 155, 192) # 画笔颜色setheading(10)begin_fill()circle(5)color(160, 82, 45) # 返回或设置pencolor和fillcolorend_fill()penup()setheading(0)forward(20)pendown()pencolor(255, 155, 192)setheading(10)begin_fill()circle(5)color(160, 82, 45)end_fill()def head(x, y): # 头color((255, 155, 192), "pink")penup()goto(x, y)setheading(0)pendown()begin_fill()setheading(180)circle(300, -30)circle(100, -60)circle(80, -100)circle(150, -20)circle(60, -95)setheading(161)circle(-300, 15)penup()goto(-100, 100)pendown()setheading(-30)a = 0.4for i in range(60):if 0 <= i < 30 or 60 <= i < 90:a = a + 0.08lt(3) # 向左转3度fd(a) # 向前走a的步长else:a = a - 0.08lt(3)fd(a)end_fill()def cheek(x, y): # 腮color((255, 155, 192))penup()goto(x, y)