python之海龟绘图

这篇博客通过Python的turtle模块展示了如何绘制奥运五环和樱花纷飞的图案。代码中详细解释了使用turtle库进行图形绘制的基本语句,如设置线条颜色、宽度,移动和旋转等。通过递归函数实现了樱花树的枝干和花瓣的随机生成,营造出樱花飘落的效果。这是一个结合艺术与编程的有趣实例,适合初学者学习Python图形编程。
摘要由CSDN通过智能技术生成
以下内容采用的是pycharm软件
海龟绘图的基本语句
import turtle   #导入海龟绘图工具
turtle.showturtle()    #显示箭头
turtle.width()         #显示线条宽度
turtle.write()         #书写
turtle.forward()       #前进多少个像素
turtle.color()         #改变笔的颜色
turtle.left('度数')     #笔左转多少度
turtle.goto()          #去什么坐标                       以原点为坐标(0,0)
turtle.penup()         #抬起笔
turtle.pendown()       #落笔
turtle.circle()        #画圈   ()内填半径大小
turtle.done            #结束程序,窗口保持。

奥运五环代码

import turtle

#最好的老师:兴趣   第二个好老师:耻辱

#第一个圈
turtle.width(10)
turtle.color("blue")
turtle.circle(50)

#第二个圈
turtle.penup()
turtle.goto(80,0)
turtle.pendown()
turtle.color("black")
turtle.circle(50)

#第三个圈
turtle.penup()
turtle.goto(160,0)
turtle.pendown()
turtle.color("red")
turtle.circle(50)

#第四个圈
turtle.penup()
turtle.goto(40,-60)
turtle.pendown()
turtle.color("yellow")
turtle.circle(50)

#第五个圈
turtle.penup()
turtle.goto(110,-60)
turtle.pendown()
turtle.color("green")
turtle.circle(50)

turtle.done()  #程序结束,保持窗口

运行结果图

图因为涉及奥运五环所以展示不出来。

 樱花纷飞代码

import turtle as T
import random
import time
 
# 画樱花的躯干(60,t)
def Tree(branch, t):
    time.sleep(0.0005)
    if branch > 3:
        if 8 <= branch <= 12:
            if random.randint(0, 2) == 0:
                t.color('snow')  # 白
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 3)
        elif branch < 8:
            if random.randint(0, 1) == 0:
                t.color('snow')
            else:
                t.color('lightcoral')  # 淡珊瑚色
            t.pensize(branch / 2)
        else:
            t.color('sienna')  # 赭(zhě)色
            t.pensize(branch / 10)  # 6
        t.forward(branch)
        a = 1.5 * random.random()
        t.right(20 * a)
        b = 1.5 * random.random()
        Tree(branch - 10 * b, t)
        t.left(40 * a)
        Tree(branch - 10 * b, t)
        t.right(20 * a)
        t.up()
        t.backward(branch)
        t.down()
 
# 掉落的花瓣
def Petal(m, t):
    for i in range(m):
        a = 200 - 400 * random.random()
        b = 10 - 20 * random.random()
        t.up()
        t.forward(b)
        t.left(90)
        t.forward(a)
        t.down()
        t.color('lightcoral')  # 淡珊瑚色
        t.circle(1)
        t.up()
        t.backward(a)
        t.right(90)
        t.backward(b)
 
# 绘图区域
t = T.Turtle()
# 画布大小
w = T.Screen()
t.hideturtle()  # 隐藏画笔
t.getscreen().tracer(5, 0)
w.screensize(bg='wheat')  # wheat小麦
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')
 
# 画樱花的躯干
Tree(60, t)
# 掉落的花瓣
Petal(100, t)
w.exitonclick()

运行结果:
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值