栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

3.9.python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

3.9.python

turtle是python自帶的繪圖模凷, 性能一般, 可用以簡單的作圖需求.

1.turtle模凷函數

write(), 在光標所在點打印字符串

forward(), 前進參數指定的像素長度

right(), left(), 按參數(0~360)指定的角度轉向

color(), 更改線條顏色爲參數指定的顏色, 可使用字符串, 如’red’, ‘blue’

width(), 更改線條寬度爲參數指定的像素寬度

goto(), 移動到參數指定的坐標點

penup(), 提起畫筆, 避免在移動時留下線條

pendown(), 放下畫筆, 使能畫出線條

circle(), 按參數指定的半徑長度作圓

done(), 避免繪圖窗口閃退, 等待人爲關閉


2.實例

1.繪製五角星
# 繪製五角星
import turtle as tt

length = 200
tt.width(3)
tt.color('blue')

tt.forward(length)
tt.right(144)  # 角度調整, 五角星內角爲36度, 由幾何知識可得, 應旋轉180-36=144度
tt.forward(length)
tt.right(144)
tt.forward(length)
tt.right(144)
tt.forward(length)
tt.right(144)
tt.forward(length)

tt.done()

實現如下圖, 變色和加粗只需要在中間步驟穿插幾个函數: 

 2.繪製五環
# 繪製OlympicSymbol
import turtle

radius = 45  # 五環半徑
turtle.width(5)  # 線條粗細
turtle.hideturtle()  # 隱藏光標

# 從左上藍環開始
turtle.color('blue')  # 改變線條顏色
turtle.circle(radius)  # 按半徑畫圓

turtle.color('yellow')
turtle.penup()  # 提起畫筆, 避免移動時上色
turtle.goto(50, -50)  # 移動到下一个圓心
turtle.pendown()  # 落下畫筆, 開始上色
turtle.circle(radius)

turtle.color('black')
turtle.penup()
turtle.goto(100, 0)
turtle.pendown()
turtle.circle(radius)

turtle.color('green')
turtle.penup()
turtle.goto(150, -50)
turtle.pendown()
turtle.circle(radius)

turtle.color('red')
turtle.penup()
turtle.goto(200, 0)
turtle.pendown()
turtle.circle(radius)

turtle.done()  # 避免繪圖窗口閃退, 等待人爲關閉

實現如下圖所示:

 3.繪製復雜圖案:
# turtle繪圖: 繪製旋轉的正多邊形
import turtle as tt


def regular_polygon_flower(sides=4, num=60, length=100):
    """
    使用turtle繪製正多邊形旋轉構成的閉合花形
    """
    for i in range(num):
        for j in range(sides):
            tt.forward(length)
            tt.right(180 - ((sides - 2) * 180 / sides))
        tt.right(360 / num)


def turtle_spiral(sides=4, num=60, length=20):
    """
    使用turtle繪製正多邊形旋轉構成的螺線
    """
    for i in range(num):
        for j in range(sides):
            tt.forward(length)
            tt.right(180 - ((sides - 2) * 180 / sides))  # 任意正多邊形的角度公式
        tt.right(360 / num)
        length += 2


if __name__ == '__main__':
    tt.hideturtle()
    regular_polygon_flower(sides=9, num=25, length=100)
    # turtle_spiral(sides=5, num=180, length=10)
    tt.done()

這裡結合循環語句定義了兩个函數, 實現如下圖:

首先是旋轉的正多邊形:

 正方形(上), 六邊形(下):

 然後是多邊形旋轉形成的螺線:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/886566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号