Python Turtle 模組繪製國旗

2021-03-01 12:00:18

Python Turtle 模組繪製國旗

Python Turtle 模組繪製國旗
turtle模組:python內建的繪圖工具

基本操作(Turtle方法)

turtle.forward(step):前進step個畫素
turtle.back(step):後退step個畫素
turtle.right():右轉一個角度
turtle.left():左轉一個角度
turtle.pencolor(「string」):畫筆顏色
turtle.fillcolor(「string」):填充顏色
turtle.speed(int):運動速度

其他的turtle方法可以參見python官網

https://docs.python.org/zh-cn/3.7/library/turtle.html

具體程式碼實現

# 繪畫
# 中國國旗
# 轉載請標明出處!!


import turtle
import time


def draw__stars(tur, step, x, y, arg):
    """
    繪製五角星
    :param tur: turtle object
    :param step: 五角星一條邊的長度
    :param x: 開始繪製五角星的起點x座標
    :param y: 開始繪製五角星的起點y座標
    :param arg:
    :return:
    """
    tur.pencolor('yellow')
    tur.fillcolor('yellow')
    tur.up()
    tur.goto(x, y)
    tur.begin_fill()
    tur.down()
    tur.right(arg)
    tur.forward(step)
    tur.right(144)
    tur.forward(step)
    tur.right(144)
    tur.forward(step)
    tur.right(144)
    tur.forward(step)
    tur.right(144)
    tur.forward(step)
    tur.right(144)
    tur.end_fill()


def draw__flag(tur, wide, height):
    """
    繪製國旗的長方形形狀
    :param tur: turtle object
    :param wide: the width of the flag
    :param height: the height of the flag
    :return: None
    """
    tur.pencolor('red')
    tur.fillcolor('red')
    tur.goto(- wide / 2, height / 2)
    tur.begin_fill()
    tur.forward(wide)
    tur.right(90)
    tur.forward(height)
    tur.right(90)
    tur.forward(wide)
    tur.right(90)
    tur.forward(height)
    tur.end_fill()


if __name__ == '__main__':
    """
    main 函數
    """
    # tur = turtle.Turtle()
    turtle.screensize(canvwidth=3000, canvheight=2000, bg=None)
    # 繪製star的turtle物件
    tur_star = turtle.Turtle()
    # 繪製flag的turtle物件
    tur_flag = turtle.Turtle()
    tur_flag.speed(3)
    tur_star.speed(3)
    # 隱藏turtle物件
    tur_star.hideturtle()
    tur_flag.hideturtle()
    # 間隔3秒,可以沒有,這個是我偵錯時加上去的
    time.sleep(3)
    # 繪製長方形
    draw__flag(tur_flag, 630, 420)
    # 繪製五角星,在合適的位置進行繪製五角星
    # 呼叫五次函數繪製五顆五角星
    draw__stars(tur_star, step=60, x=-280, y=155, arg=0)
    draw__stars(tur_star, step=25, x=-182, y=177, arg=- 25)
    draw__stars(tur_star, step=25, x=-175, y=125, arg=41)
    draw__stars(tur_star, step=25, x=-208, y=79, arg=23)
    draw__stars(tur_star, step=25, x=-265, y=75, arg=48)
    # 使畫面鎖定
    turtle.done()


執行結果

運行結果