少儿学编程系列---使用python turtle画熊猫
turtle简介
Turtle库是Python语言中一个很流行的绘制图像的函数库,利用它可以绘制图形,非常适合于引导少儿学习编程。
常用绘图命令
绘图有着许多的命令,这些命令可以划分为3种:运动命令,画笔控制命令和全局控制命令
画笔运动命令
forward(distance) 向当前画笔方向移动distance像素长
backward(distance) 向当前画笔相反方向移动distance像素长度
right(degree) 顺时针移动degree°
left(degree) 逆时针移动degree°
pendown() 移动时绘制图形,缺省时也为绘制
penup() 移动时不绘制图形,提起笔,用于另起一个地方绘制时用
goto(x,y) 将画笔移动到坐标为x,y的位置
setpos(x,y) 将画笔移动到坐标为x,y的位置
speed(speed) 画笔绘制的速度范围[0,10]整数
circle(radius) 画圆,半径为正(负),表示圆心在画笔的左边(右边)画圆
画笔控制命令
pensize(width) 绘制图形时的宽度
pencolor(color) 画笔颜色
fillcolor(color) 绘制图形的填充颜色
color(color1, color2) 同时设置pencolor=color1, fillcolor=color2
filling() 返回当前是否在填充状态
begin_fill() 准备开始填充图形
end_fill() 填充完成;
hideturtle() 隐藏箭头显示;
showturtle() 显示箭头显示;
全局控制命令
clear() 清空turtle窗口,但是turtle的位置和状态不会改变
reset() 清空窗口,重置turtle状态为起始状态
undo() 撤销上一个turtle动作
isvisible() 返回当前turtle是否可见
stamp() 复制当前图形
write(s[,font=("font-name",font_size,"font_type")]) 写文本,s为文本内容,font是字体的参数,里面分别为字体名称,大小和类型;font为可选项, font的参数也是可选项
熊猫效果展示
画熊猫的代码
# 使用海龟图形绘制熊猫
# 导入turtle包下的所有方法
from turtle import *
import time
# 画动态半径彩色圆
def ring(col, rad):
fillcolor(col)
begin_fill()
circle(rad)
end_fill()
# 画耳朵
def draw_ears(x, y):
#画左耳
up()
setpos(-35 - x, 95 - y)
down()
ring('black', 15)
# 画右耳
up()
setpos(35 - x, 95 - y)
down()
ring('black', 15)
# 画脸
def draw_face(x, y):
up()
setpos(0 - x, 35 - y)
down()
ring('white', 40)
def draw_eyes(x, y):
# Draw first eye
up()
setpos(-18 - x, 75 - y)
down
ring('black', 8)
# Draw second eye
up()
setpos(18 - x, 75 - y)
down()
ring('black', 8)
# Draw first eye
up()
setpos(-18 - x, 77 - y)
down()
ring('white', 4)
# Draw second eye
up()
setpos(18 - x, 77 - y)
down()
ring('white', 4)
def draw_nose(x, y):
up()
setpos(0 - x, 55 - y)
down()
ring('black', 5)
def draw_mouth(x, y):
up()
setpos(0 - x, 55 - y)
down()
right(90)
circle(5, 180)
up()
setpos(0 - x, 55 - y)
down()
left(360)
circle(5, -180)
def draw_pandas(x, y):
draw_ears(x, y)
draw_face(x, y)
draw_eyes(x, y)
draw_nose(x, y)
draw_mouth(x, y)
def main():
speed(20)
bgcolor("blue")
draw_pandas(200, 0)
right(270)
draw_pandas(0, 0)
right(270)
draw_pandas(-200, 0)
right(270)
draw_pandas(200, 200)
right(270)
draw_pandas(0, 200)
right(270)
draw_pandas(-200, 200)
hideturtle()
done()
if __name__ == "__main__":
hideturtle()
up()
goto(-260, 270)
write("今天头条-cloudcoder出品", align='left', font=('fangsong', 20, 'normal'))
time.sleep(1)
showturtle()
main()