turtle库的几个案例进阶,代码可直接运行(python经典编程案例)

简介: 该文章展示了使用Python的turtle库进行绘图的进阶案例,包括绘制彩色圆形和复杂图案的代码示例。

1. 画出奥运五环图

代码如下:

import turtle
turtle.width(10)
turtle.color("blue")
turtle.circle(50)

turtle.color("black")
turtle.penup()
turtle.goto(120, 0)
turtle.pendown()
turtle.circle(50)

turtle.color("red")
turtle.penup()
turtle.goto(240, 0)
turtle.pendown()
turtle.circle(50)

turtle.color("yellow")
turtle.penup()
turtle.goto(60, -50)
turtle.pendown()
turtle.circle(50)

turtle.color("green")
turtle.penup()
turtle.goto(180, -50)
turtle.pendown()
turtle.circle(50)

执行结果如下图所示:
在这里插入图片描述

2. 定义多点坐标并计算起始点和终点距离

import turtle
import math

# 定义多个点的坐标
x1, y1 = 100, 100
x2, y2 = 100, -100
x3, y3 = -100, -100
x4, y4 = -100, 100

# 绘制折线
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()

turtle.goto(x2, y2)
turtle.goto(x3, y3)
turtle.goto(x4, y4)

# 计算起始点和终点的距离
distance = math.sqrt((x1-x4)**2 + (y1-y4)**2)
turtle.write(distance)

在这里插入图片描述

3. 画玫瑰

用Python 画出玫瑰图案,代码如下:

import turtle as t

# 定义一个曲线绘制函数
def DegreeCurve(n, r, d=1):
    for i in range(n):
        t.left(d)
        t.circle(r, abs(d))
# 初始位置设定
s = 0.2 # size
t.setup(450*5*s, 750*5*s)
t.pencolor("black")
t.fillcolor("red")
t.speed(100)
t.penup()
t.goto(0, 900*s)
t.pendown()
# 绘制花朵形状
t.begin_fill()
t.circle(200*s,30)
DegreeCurve(60, 50*s)
t.circle(200*s,30)
DegreeCurve(4, 100*s)
t.circle(200*s,50)
DegreeCurve(50, 50*s)
t.circle(350*s,65)
DegreeCurve(40, 70*s)
t.circle(150*s,50)
DegreeCurve(20, 50*s, -1)
t.circle(400*s,60)
DegreeCurve(18, 50*s)
t.fd(250*s)
t.right(150)
t.circle(-500*s,12)
t.left(140)
t.circle(550*s,110)
t.left(27)
t.circle(650*s,100)
t.left(130)
t.circle(-300*s,20)
t.right(123)
t.circle(220*s,57)
t.end_fill()
# 绘制花枝形状
t.left(120)
t.fd(280*s)
t.left(115)
t.circle(300*s,33)
t.left(180)
t.circle(-300*s,33)
DegreeCurve(70, 225*s, -1)
t.circle(350*s,104)
t.left(90)
t.circle(200*s,105)
t.circle(-500*s,63)
t.penup()
t.goto(170*s,-30*s)
t.pendown()
t.left(160)
DegreeCurve(20, 2500*s)
DegreeCurve(220, 250*s, -1)
# 绘制一个绿色叶子
t.fillcolor('green')
t.penup()
t.goto(670*s,-180*s)
t.pendown()
t.right(140)
t.begin_fill()
t.circle(300*s,120)
t.left(60)
t.circle(300*s,120)
t.end_fill()
t.penup()
t.goto(180*s,-550*s)
t.pendown()
t.right(85)
t.circle(600*s,40)
# 绘制另一个绿色叶子
t.penup()
t.goto(-150*s,-1000*s)
t.pendown()
t.begin_fill()
t.rt(120)
t.circle(300*s,115)
t.left(75)
t.circle(300*s,100)
t.end_fill()
t.penup()
t.goto(430*s,-1070*s)
t.pendown()
t.right(30)
t.circle(-600*s,35)
t.done()

执行结果如下图:
在这里插入图片描述

4. 绘制多个同心圆

代码如下

import turtle

t = turtle.Pen()
my_colors = ("red", "green", "yellow", "black")
t.width(4)
t.speed(1)
for i in range(10):  # 0 1 2 3 4
    t.penup()
    t.goto(0, -i*10)  # 0, -100,-200,-300,-400
    t.pendown()
    t.color(my_colors[i%len(my_colors)])
    t.circle(15+i*10)  # 100,200,300, 400,, 500
turtle.done()  # 程序执行完,窗口仍然在

执行结果如下图:
在这里插入图片描述

5. 用Python 绘制 18*18 棋盘

import turtle
width = 30
num = 18
x1 = [(-400, 400), (-400+width*num, 400)]
y1 = [(-400, 400), (-400, 400-width*num)]
t = turtle.Pen()
t.speed(10)
for i in range(0, 19):
    t.penup()
    t.goto(x1[0][0], x1[0][1]-30*i)
    t.pendown()
    t.goto(x1[1][0], x1[1][1]-30*i)
for i in range(0, 19):
    t.penup()
    t.goto(y1[0][0]+30*i,y1[0][1])
    t.pendown()
    t.goto(y1[1][0]+30*i,y1[1][1])
t.hideturtle()  # 隐藏画笔
turtle.done()  # 保证运行窗口不被自动关闭

6. 画樱花

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(200, t)
w.exitonclick()

7. 画圣诞树

# -*- encoding: utf-8 -*-
"""
@Author: cuiyonghua
@CreateDate: 2020/12/15 8:05 下午
@File: 画圣诞树.py
@Description: 
"""
import turtle  # 导入绘图海龟模块

turtle.setup(500, 600)  # 设置窗体大小
tree = turtle.Turtle()  # 创建画笔
tree.shape('triangle')  # 默认为三角形
tree.color('green')  # 设置画笔颜色
tree.right(30)  # 向右旋转30度
tree.up()  # 抬起画笔


# 绘制树
def drawing_tree(start, stop, move, is_square=False):
    if is_square:  # 该参数为True说明绘制树干
        tree.left(30)  # 向左旋转30度
        tree.shape('square')  # 设置绘制物为正方形
        tree.color('brown')  # 设置颜色为棕色
    for r in range(start, stop):  # 循环遍历行的绘制物
        a = r  # 默认绘制树叶
        if is_square:  # 该参数为True说明绘制树干
            a = 1  # 将a设置为1,只绘制一列图形
        y = 20 * r  # 计算绘制物y坐标的距离
        for c in range(a):  # 循环遍历列的绘制物
            x = 20 * c  # 计算绘制物x坐标的距离
            tree.goto(x, -y + move)  # 移动右半部分的位置
            tree.stamp()  # 复制当前图形,实现绘制
            tree.goto(-x, -y + move)  # 移动左半部分的位置
            tree.stamp()  # 复制当前图形,实现绘制


drawing_tree(1, 4, 160)  # 绘制圣诞树的前三层
drawing_tree(2, 5, 120)  # 绘制圣诞树的中间三层
drawing_tree(3, 6, 80)  # 绘制圣诞树的最后三层
drawing_tree(4, 9, 40, True)  # 绘制圣诞树的树干

import time  # 导入时间模块

word = turtle.Turtle()  # 创建绘制文字的画笔对象
word.up()  # 抬起画笔
word.goto(-150, 200)  # 移动到顶部位置
word.color('red')  # 设置画笔颜色为红色
# 写入文字“圣”
word.write("圣", font=(u"黑体", 48, "normal"), align="center")
time.sleep(0.5)  # 等待指定时间
word.goto(-50, 200)  # 画笔移动至第二个字的位置
# 写入文字“诞”
word.write(arg="诞", move=True, font=(u"黑体", 48, "normal"), align="center")
time.sleep(0.5)  # 等待指定时间
word.goto(50, 200)  # 画笔移动至第三个字的位置
# 写入文字“快”
word.write("快", font=(u"黑体", 48, "normal"), align="center")
time.sleep(0.5)  # 等待指定时间
word.goto(150, 200)  # 画笔移动至第四个字的位置
# 写入文字“乐”
word.write("乐", font=(u"黑体", 48, "normal"), align="center")
word.hideturtle()  # 隐藏箭头
turtle.mainloop()  # 开始循环防止窗口自动关闭

8. 动态时钟

# -*- encoding: utf-8 -*-
"""
@Author: cuiyonghua
@CreateDate: 2020/12/15 7:56 下午
@File: 动态时钟.py
@Description: 
"""
'''
动态时钟
'''
import turtle
import datetime


# 移动一段距离
def skip(distance):  # 移动方法,不留移动痕迹
    turtle.penup()  # 抬笔不绘制
    turtle.forward(distance)  # 移动指定距离
    turtle.pendown()  # 落笔移动绘制


def draw_clock_dial():  # 绘制表盘的方法
    turtle.reset()  # 删除图形归位
    turtle.hideturtle()  # 隐藏箭头
    for i in range(60):  # 循环执行60次,一圈为360度所以每一秒的角度为6度
        skip(160)  # 移动160,相当于表盘圆的半径
        # 每5秒绘制一个小时刻度
        if i % 5 == 0:
            turtle.pensize(7)  # 刻度大小
            # 画时钟
            turtle.forward(20)  # 小时刻度的长度为20
            # if i == 0:               # 判断第一个位置为12点
            #     # 写入数字12
            #     turtle.write(12, align='center', font=('Courier', 14, 'bold'))
            # elif i == 25 or i == 30 or i == 35:    # 5、6、7
            #     skip(25)   # 避免与刻度重叠,所以多移动一段距离
            #     # 根据i除以5获取,5点、6点、7点并写入对应的数字
            #     turtle.write(int(i/5), align='center', font=('Courier', 14, 'bold'))
            #     skip(-25)  # 回到原位置
            # else:
            #     # 根据i除以5获取其它时间的数字并写入
            #     turtle.write(int(i/5), align='center', font=('Courier', 14, 'bold'))
            skip(-20)  # 复原小时刻度的位置
        else:
            turtle.pensize(1)  # 将画笔大小设置为1
            turtle.dot()  # 绘制分钟刻度的小圆点
        skip(-160)  # 回到中心位置
        turtle.right(6)  # 向右旋转6度


def get_week(t):  # 获取星期的方法
    week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    return week[t.weekday()]  # 返回当天的星期


def create_pointer(length, name):  # 创建指针方法
    turtle.reset()  # 删除图形归位
    skip(-length * 0.1)  # 抬笔移动指定距离
    turtle.begin_poly()  # 记录多边形
    turtle.forward(length * 1.1)  # 绘制指定长度的指针
    turtle.end_poly()  # 停止记录多边形
    # 注册多边形状
    turtle.register_shape(name, turtle.get_poly())


def init_pointer():  # 初始化指针
    global secHand, minHand, hurHand, printer
    turtle.mode("logo")  # 重置Turtle指向上
    create_pointer(135, "secHand")  # 创建秒针图形
    create_pointer(110, "minHand")  # 创建分针图形
    create_pointer(90, "hurHand")  # 创建时针图形
    secHand = turtle.Turtle()  # 创建秒针turtle对象
    secHand.shape("secHand")  # 创建指定秒针名称的形状
    minHand = turtle.Turtle()  # 创建分针turtle对象
    minHand.shape("minHand")  # 创建指定分针名称的形状
    hurHand = turtle.Turtle()  # 创建时针turtle对象
    hurHand.shape("hurHand")  # 创建指定时针名称的形状
    for hand in secHand, minHand, hurHand:  # 循环遍历三个指针
        hand.shapesize(1, 1, 5)  # 设置形状拉伸大小和轮廓线
        hand.speed(0)  # 设置速度为最快
    printer = turtle.Turtle()  # 创建绘制文字的Turtle对象
    printer.hideturtle()  # 隐藏箭头
    printer.penup()  # 抬笔


def move_pointer():  # 移动指针的方法
    # 不停的获取时间
    t = datetime.datetime.today()
    second = t.second + t.microsecond * 0.000001  # 计算移动的秒
    minute = t.minute + second / 60  # 计算移动的分
    hour = t.hour + minute / 60  # 计算移动的小时
    secHand.setheading(6 * second)  # 设置秒针的角度
    minHand.setheading(6 * minute)  # 设置分针的角度
    hurHand.setheading(30 * hour)  # 设置时针的角度
    turtle.tracer(False)  # 关闭绘画效果
    printer.forward(65)  # 向上移动65
    # 绘制星期
    printer.write(get_week(t), align="center", font=("Courier", 14, "bold"))
    printer.back(130)  # 倒退130
    # 绘制年月日
    printer.write(t.strftime('%Y-%m-%d'), align="center", font=("Courier", 14, "bold"))
    printer.home()  # 归位
    turtle.tracer(True)  # 开启绘画效果
    turtle.ontimer(move_pointer, 10)  # 10毫秒后调用move_pointer()方法


if __name__ == '__main__':
    turtle.setup(450, 450)  # 创建窗体大小
    init_pointer()  # 调用初始化指针的方法
    turtle.tracer(False)  # 关闭绘画效果
    draw_clock_dial()  # 绘制表盘
    move_pointer()  # 调用移动指针的方法
    turtle.mainloop()  # 不关闭窗体

9. 六边形和螺旋线


# -*- encoding: utf-8 -*-
"""
@Author: cuiyonghua
@CreateDate: 2020/10/19 3:05 下午
@Description:
"""
import turtle

t = turtle.Pen()
turtle.bgcolor("black")
sides = 6
colors = ['red', 'yellow', 'green', 'blue', 'orange', 'purple']

# 炫酷六边形
for x in range(360):
    t.pencolor(colors[x%sides])
    t.forward(x*3/sides+x)
    t.left(360/sides+1)
    t.width(x*sides/180)
    t.left(91)

# 一. 漂亮的螺旋线
# for x in range(260):
#     t.pencolor(colors[x % sides])
#     t.forward(x * 3 / sides + x)
#     t.left(360 / sides + 1)
#     t.width(x * sides / 200)

10. 画分形树

from turtle import *

# 设置色彩模式是RGB:
colormode(255)

lt(90)

lv = 14
l = 120
s = 45

width(lv)

# 初始化RGB颜色:
r = 0
g = 0
b = 0
pencolor(r, g, b)

penup()
bk(l)
pendown()
fd(l)

def draw_tree(l, level):
    global r, g, b
    # save the current pen width
    w = width()

    # narrow the pen width
    width(w * 3.0 / 4.0)
    # set color:
    r = r + 1
    g = g + 2
    b = b + 3
    pencolor(r % 200, g % 200, b % 200)

    l = 3.0 / 4.0 * l

    lt(s)
    fd(l)

    if level < lv:
        draw_tree(l, level + 1)
    bk(l)
    rt(2 * s)
    fd(l)

    if level < lv:
        draw_tree(l, level + 1)
    bk(l)
    lt(s)

    # restore the previous pen width
    width(w)

speed("fastest")

draw_tree(l, 4)

done()
相关文章
|
1天前
|
Shell Linux Python
python执行linux系统命令的几种方法(python3经典编程案例)
文章介绍了多种使用Python执行Linux系统命令的方法,包括使用os模块的不同函数以及subprocess模块来调用shell命令并处理其输出。
8 0
|
1天前
|
调度 数据库 Python
python中APScheduler的使用详解(python3经典编程案例)
文章详细讲解了在Python中使用APScheduler来安排和执行定时任务的方法,包括不同调度器的配置与使用场景。
9 0
|
1天前
|
数据可视化 搜索推荐 JavaScript
pyecharts模块的几个经典案例(python经典编程案例)
文章提供了多个使用pyecharts模块创建数据可视化的Python编程案例,展示如何生成各种类型的图表并进行定制化设置。
7 0
|
1天前
|
机器学习/深度学习 开发工具 git
matplotlib各种案例总结(python经典编程案例)
该文章汇总了使用matplotlib绘制不同类型图表的方法和案例,包括条形图、折线图等,并展示了如何调整颜色和线条样式等属性。
8 0
|
1天前
|
数据挖掘 Python
用python的tushare模块分析股票案例(python3经典编程案例)
该文章提供了使用Python的tushare模块分析股票数据的案例,展示了如何获取股票数据以及进行基本的数据分析。
9 0
|
1天前
|
存储 数据库 Python
python的对象数据库ZODB的使用(python3经典编程案例)
该文章介绍了如何使用Python的对象数据库ZODB来进行数据存储,包括ZODB的基本操作如创建数据库、存储和检索对象等,并提供了示例代码。
8 0
|
1天前
|
JSON NoSQL 数据库
和SQLite数据库对应的NoSQL数据库:TinyDB的详细使用(python3经典编程案例)
该文章详细介绍了TinyDB这一轻量级NoSQL数据库的使用方法,包括如何在Python3环境中安装、创建数据库、插入数据、查询、更新以及删除记录等操作,并提供了多个编程案例。
8 0
|
2天前
|
Python
用python实现背单词的功能(python3经典编程案例)
这篇文章介绍了如何使用Python和Tkinter库实现一个背单词的桌面应用,通过读取文本文件中的单词列表,并在GUI界面中随机显示单词及其音标和解释。
18 10
|
2天前
|
Python
在python终端中打印颜色的3中方式(python3经典编程案例)
这篇文章介绍了在Python终端中打印彩色文本的三种方式:使用`colorama`模块、`termcolor`模块和ANSI转义码。
18 8