不間斷 Python 挑戰 Day 24 - Turtle Graphics繪圖模組

2022/02/08閱讀時間約 13 分鐘
Turtle Graphic的前身是一種設計給小朋友學習的簡易繪圖程式,最初來自於Wally Feurzeig、Seymour Papert和Cynthia Solomon於1967年所創造的Logo編程語言,它是Python內建的繪圖函式庫,我們可以根據函式庫裡面的指令,操控一隻或多隻「小烏龜」在帶有平面座標的「畫布」上移動,小烏龜帶有畫筆,在它移動的軌跡上,可以讓畫筆提起或放下來決定畫或不畫出線條。本節會介紹一些基本的用法,詳細的內容可以參閱官方文件

畫布 (Canvas)

在繪製圖形之前,首先必須要有可以繪製圖形的區域,也稱為畫布。以下程式載入turtle模組,並建立Screen的物件,最後再呼叫exitonclick()方法讓使用者點一下畫布後再結束程式,以免程式執行後畫布閃一下即消失。
from turtle import Screen
screen = Screen()
screen.exitonclick()
執行結果:

背景顏色

以下三種方式可以設定畫布的背景顏色:
screen.bgcolor(顏色字串)
  顏色字串可參考:https://www.tcl.tk/man/tcl8.4/TkCmd/colors.html
例如:
screen.bgcolor("green")
screen.bgcolor(hex code number)
  hex code number可參考:https://en.wikipedia.org/wiki/Web_colors
例如:
screen.bgcolor("#008000")
screen.bgcolor(r, g, b)
  其中r、g、b的範圍由screen.colormode(cmode)決定,預設為1,cmode可為1或255,r、g、b必須介於0到cmode之間,例如:
screen.colormode(255)
screen.bgcolor(0, 255, 0)
執行結果皆為設定畫布背景為綠色:

標題

screen.title(titlestring)
  可改變畫布左上角的標題,例如:
screen.title("我的畫布")

視窗大小與位置

screen.setup(width=_CFG['width'], height=_CFG['height'], startx=_CFG['leftright'], starty=_CFG['topbottom'])
  可設置畫布主視窗的大小與位置,width與height若為整數表示像素、若為浮點數則表示螢幕的占比;startx若為正數表示距離左邊緣多少像素、若為負數表示距離右邊緣多少像素;starty若為正數表示距離上邊緣多少像素、若為負數表示距離右下邊緣多少像素。

清除繪圖

screen.clear()
screen.clearscreen()
  可將畫布上的所有繪圖清除。

畫筆

有了畫布之後,載入turtle模組並建立Turtle的物件,執行後便可看到畫布中央多了一個預設為向右的箭頭,預設的位置即為畫布的原點,也是畫布的中心點,向右為x軸的正向、向上為y軸的正向,以此訂出畫布的座標系統。
from turtle import Turtle
turtle = Turtle()

前進、後退

turtle.forward(distance)
turtle.fd(distance)
  往原本的方向前進distance指定的距離(像素)。
turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
  後退distance指定的距離(像素),不改變畫筆的朝向
以下範例讓畫筆前進100步再後退100步。
turtle.forward(100)
turtle.backward(100)

移至定點

turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)
  將畫筆移動到座標(x, y)的地方,整個畫布以中心為原點(0, 0),向右為x軸正向、向上為y軸正向,如以下範例建立一個600*600大小的畫布,把畫筆移動到(-200, 200)的位置。
screen.setup(600, 600)
turtle.goto(-200, 200)
turtle.setx(x)
  將畫筆移動到指定的x座標。
turtle.sety(y)
  將畫筆移動到指定的y座標。
如下例最後停止的位置和前例相同,但軌跡不同。
turtle.setx(-200)
turtle.sety(200)

回到原點

turtle.home()
  回到畫布中心(0, 0)的位置。

速度

turtle.speed(speed=None)
  設定畫筆移動的速度,範圍在0到10之間,除了0以外,數字愈大畫筆移動的速度愈快,也可以使用文字做為參數輸入,和數字的對應如下:
  • “fastest”: 0
  • “fast”: 10
  • “normal”: 6
  • “slow”: 3
  • “slowest”: 1

提筆下筆

turtle.penup()
turtle.pu()
turtle.up()
  畫筆移動時不畫出軌跡。
turtle.pendown()
turtle.pd()
turtle.down()
  畫筆移動時畫出軌跡。
先使用penup()方法,再移動至指定座標,過程中便不會畫出移動軌跡。
turtle.penup()
turtle.goto(-200, 200)

顯示隱藏畫筆

turtle.showturtle()
turtle.st()
  顯示畫筆。
turtle.hideturtle()
turtle.ht()
  隱藏畫筆。

移動方向

turtle.right(angle)
turtle.rt(angle)
  右轉angle個單位,預設為角度,單位可由turtle.degrees()turtle.radians()設定。
turtle.left(angle)
turtle.lt(angle)
  左轉angle個單位,預設為角度,單位可由turtle.degrees()turtle.radians()設定。
turtle.setheading(to_angle)
turtle.seth(to_angle)
  轉至特定的角度。
至此為止,我們可以結合移動跟角度來畫出一些比較複雜的圖形。
turtle.penup()
turtle.goto(-100, 200)
turtle.pendown()
for side in range(3, 11):
  angle = 360/side
  for _ in range(side):
    turtle.forward(100)
    turtle.right(angle)

詢問位置方向

turtle.position()
turtle.pos()
  詢問畫筆的(x, y)座標。
turtle.xcor()
  詢問畫筆的x座標。
turtle.ycor()
  詢問畫筆的y座標。
turtle.heading()
  詢問畫筆的方向(角度)。

顏色

turtle.pencolor(*args)
turtle.pencolor(顏色字串)
turtle.pencolor(hex code number)
turtle.pencolor(r, g, b)
  設定畫筆軌跡與畫筆外緣的顏色,設定方式和畫布的背景顏色相同,其中r、g、b的範圍由screen.colormode(cmode)決定。
turtle.fillcolor(*args)
turtle.fillcolor(顏色字串)
turtle.fillcolor(hex code number)
turtle.fillcolor(r, g, b)
設定畫筆軌跡圍出區域與畫筆內部的填充顏色,設定方式和畫布的背景顏色相同,其中r、g、b的範圍由screen.colormode(cmode)決定。
turtle.color(*args)
  當輸入一個參數時,會同時設定pencolor和fillcolor;當輸入兩個參數時,第一個參數設定pencolor,第二個參數設定fillcolor。參數的設定方式和pencolor及fillcolor相同。

填充顏色

turtle.begin_fill()
turtle.end_fill()
  在開始繪製圖形的前後分別呼叫turtle.begin_fill()及turtle.end_fill(),在繪製結束後填充顏色到繪製區域內。
screen.colormode(255)
turtle.fillcolor(0, 255, 0)
turtle.penup()
turtle.goto(-50, 0)
turtle.pendown()
turtle.begin_fill()
for _ in range(5):
  turtle.forward(100)
  turtle.left(144)
turtle.end_fill()

寫字

turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
  畫布上面也可以寫文字,參數設定方式如下:
  • arg – 文字內容。
  • move – 設為True時,畫筆會移動到文字的右下角。
  • align – 對齊方式,可為"left"(置左)、"center"(置中)或"right"(置右)。
  • font – 以元組的形式設定字體(font)、字體大小(font size)、以及字型(font type)
turtle.write("Hello 你好!", move=False, align="center", font=("Arial", 20, "bold"))

畫筆形狀

turtle.shape(name=None)
  目前為止我們看到的畫筆筆頭預設都是箭頭的形狀,也可以換成以下這些形狀:"arrow"、"turtle"、"circle"、"square"、"triangle"、"classic"。
既然這個模組名稱叫Turtle graphics,怎麼可以沒有小烏龜呢?讓小烏龜跑起來吧!這個範例中建立了五個Turtle物件,分別有不同的顏色、位置,並由亂數每次隨機選擇一隻小烏龜往前跑10步,就像是一個烏龜賽跑的遊戲,看看誰會先跑到終點!
註1:程式在初始化Turtle物件時同時傳入參數將畫筆設為"Turtle",並隱藏畫筆,使畫面上看不到畫筆設定的轉換及移動至定位的過程,增加視覺上的流暢度。
註2:程式中引入了time模組中的sleep()方法,讓程式執行過程中停頓所設定的秒數,以避免動作之間過於密集。
import random
import time
turtle_list = []
turtle_color_list = ["green", "blue", "red", "yellow", "purple"]
turtle_start_x = -280
turtle_start_y = -200
for player in range(5):
  turtle = Turtle(shape="turtle", visible=False)
  turtle.color(turtle_color_list[player])
  turtle.penup()
  turtle.goto(turtle_start_x, turtle_start_y)
  turtle.showturtle()
  turtle_list.append(turtle)
  turtle_start_y += 100
time.sleep(1)
is_race_on = True
while is_race_on:
  time.sleep(0.04)
  player = random.randint(0, 4)
  turtle_list[player].forward(10)
  if turtle_list[player].xcor() > 260:
    is_race_on = False

程式範例

為什麼會看到廣告
Wei-Jie Weng
Wei-Jie Weng
留言0
查看全部
發表第一個留言支持創作者!