Python 不只能做数学题、判断对错、写小游戏……它还能画画!今天,我们来认识一个特别有趣的模块——turtle,让我们用代码“挥舞画笔”,画出你脑海中的创意图案!
一、谁是 turtle?
是 Python 自带的绘图工具,名字的意思是“海龟”。你可以把它想象成屏幕上的一只小乌龟,它会按照你的指令爬来爬去、画出轨迹。
二、最简单的 turtle 程序
import turtle
turtle.forward(100) # 向前走 100 步
turtle.done() # 停止绘图窗口自动关闭运行后,你会看到一条直线!这就是乌龟向前走 100 像素时留下的轨迹。
三、基本命令大全(常用的就几个!)
四、用 turtle 画一个正方形
import turtle
for _ in range(4):
turtle.forward(100)
turtle.right(90)
turtle.done()你看到了吧?我们又用到了 for 循环!
五、来画个五角星!
import turtle
for _ in range(5):
turtle.forward(150)
turtle.right(144)
turtle.done()✨ 每次右转 144°,就能画出漂亮的五角星。
六、配合函数用 turtle 更强大!
import turtle
def draw_star(size):
for _ in range(5):
turtle.forward(size)
turtle.right(144)
turtle.color("orange")
draw_star(100)
turtle.penup()
turtle.goto(-150, 100)
turtle.pendown()
turtle.color("blue")
draw_star(50)
turtle.done()我们用了函数、颜色、位置控制,画出两个星星!
七、挑战:画出彩虹太阳花
import turtle
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtle.bgcolor("white")
turtle.speed(0)
for i in range(60):
turtle.color(colors[i % 6])
turtle.forward(100)
turtle.right(60)
turtle.forward(100)
turtle.right(120)
turtle.done()看到了吗?这就是 Python 画图的魅力!
✏️ 小练习 1:画出你的名字首字母
提示:
用 turtle.write() 写字母 。
用 turtle.goto(x, y) 移动位置,写多个字母。
import turtle
turtle.penup()
turtle.goto(-50, 0)
turtle.pendown()
turtle.write("A", font=("Arial", 36, "normal"))
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
turtle.write("B", font=("Arial", 36, "normal"))
turtle.done()✏️ 小练习 2:画出彩色圆环
import turtle
turtle.bgcolor("black")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtle.speed(0)
for i in range(36):
turtle.color(colors[i % 6])
turtle.circle(100)
turtle.right(10)
turtle.done()再挑战一下自己:把这个图案变成“动态花朵”?
“点赞有美意,赞赏是鼓励”
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.