3.9.python

3.9.python,第1张

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()

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

首先是旋轉的正多邊形:

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

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

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/921366.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存