学习目标:
在前面一节当中,我们已经了解了turtle库的基本语法。现在就进行一些实战,进一步掌握turtle库的相关语法内容。
学习内容:
示例1 绘制正方形(对角线),绘制要求如下:
a. 画出一个由两个直角三角形组成的正方形,边长为180像素;
b.左上角三角形填充为黄色,右下角三角形填充为红色;
c.设置画笔的速度为1,线条为黑色;
d.画图结束后,隐藏并停止画笔;
相关代码演示:
import turtle as t
t.speed(1) #设置运行的速度为1
t.setup(800,600,0, 0)
t.fillcolor("red") #设置颜色
t.begin_fill() #开始填充颜色
t.forward(180)
t.left(90)
t.forward(180)
t.goto(0,0)
t.end_fill() #结束填充颜色
t.fillcolor("yellow")
t.begin_fill()
t.forward(180)
t.right(90)
t.forward(180)
t.goto(0, 0)
t.end_fill()
t.hideturtle() #隐藏画笔
t.done() #手动退出,不然就会自动退出,不容易观察到效果
运行结果展示:
示例2 在Turtle画布上画出四叶风车,半径为100,要求:
a.风轮由4个扇叶组成,每个扇叶的大小相等,相邻两个扇叶间距相等;
b.四个扇叶的颜色分别为(红,黄,蓝,绿)。
相关代码演示:
import turtle as t
t.speed(5)
t.fillcolor("red") #设置颜色
t.begin_fill()
t.seth(0)
t.forward(100)
t.right(90)
t.circle(-100, 45)
t.goto(0,0)
t.end_fill()
t.fillcolor("green") #设置颜色
t.begin_fill()
t.seth(270)
t.forward(100)
t.right(90)
t.circle(-100, 45)
t.goto(0,0)
t.end_fill()
t.fillcolor("blue") #设置颜色
t.begin_fill()
t.seth(180)
t.forward(100)
t.right(90)
t.circle(-100, 45)
t.goto(0,0)
t.end_fill()
t.fillcolor("yellow") #设置颜色
t.begin_fill()
t.seth(90)
t.forward(100)
t.right(90)
t.circle(-100, 45)
t.goto(0,0)
t.end_fill()
t.hideturtle()
t.done()
运行结果展示:
示例3 绘制菱形,绘制要求:
a. 背景为白色,中间圆为红色轮廓线,不填充;
b. 菱形的长对角线延长线经过圆心;
c.菱形为黑色轮廓线,黄色填充,其中锐角为60度;
d.绘图过程中隐藏画笔,能清楚看见图形绘制过程。
代码演示:
import turtle as t
t.speed(10)
t.penup() #抬起画笔,不进行绘图
t.forward(120) #画笔向前移动120像素
t.pendown() #画笔落下
t.pencolor("red") #画笔的颜色为红色
t.pensize(2) #画笔的粗度为2
t.left(90)
t.circle(120)
t.penup()
t.goto(0,0)
for i in range(12):
t.pencolor("black")
t.fillcolor("yellow")
t.begin_fill()
t.penup()
t.seth(i*30)
t.forward(120)
t.pendown()
t.right(30)
t.forward(80)
t.left(60)
t.forward(80)
t.left(120)
t.forward(80)
t.left(60)
t.forward(80)
t.end_fill()
t.penup()
t.goto(0, 0)
t.hideturtle()
t.done()
运行结果展示: