使用 Python 的 Turtle 繪製一輛汽車
Turtle 是一個 Python 模組,用於使用簡單的命令建立圖形、影像和動畫。Turtle 對初學者來說是一個簡單易用的工具,可以透過建立令人興奮的視覺效果來學習程式設計。在本文中,我們將使用 Python 的 Turtle 繪製一輛汽車。
步驟 1:在 Python 中安裝 Turtle
在深入研究程式碼之前,我們需要確保 Turtle 模組已安裝在我們的 Python 環境中。使用 Python 包管理器安裝 Turtle 模組。要安裝 turtle 模組,請在終端中鍵入以下命令。
pip install turtle
步驟 2:匯入 Turtle
安裝 turtle 模組後,可以使用 Python 中的 import 命令匯入 turtle。
import turtle
步驟 3:建立 turtle 物件
匯入 Turtle 後,我們需要建立一個 Turtle 物件來進行繪製。我們可以透過呼叫 Turtle() 函式來實現 -
t = turtle.Turtle()
步驟 4:繪製汽車
建立 turtle 物件後,現在我們可以用它來建立汽車的車身。我們將前後移動 turtle 來建立汽車的頂部和底部,然後旋轉它來建立側面。然後我們可以繪製汽車的前輪、後輪和車窗。
# Draw the top of the car t.penup() t.goto(0, 50) t.pendown() t.goto(0, 100) # Draw the bottom of the car t.penup() t.goto(0, 50) t.pendown() t.goto(75, 50) t.goto(100, 75) # Draw the sides of the car t.penup() t.goto(0, 100) t.pendown() t.goto(75, 100) t.goto(100, 75) # Draw the front wheel t.penup() t.goto(25, 25) t.pendown() t.circle(25) # Draw the back wheel t.penup() t.goto(75, 25) t.pendown() t.circle(25) # Draw the windows t.penup() t.goto(15, 100) t.pendown() t.goto(60, 100) t.goto(75, 75) t.goto(60, 50) t.goto(15, 50) t.goto(0, 75) t.goto(15, 100) # Draw the headlights t.penup() t.goto(90, 75) t.dot(10)
步驟 5:新增顏色
我們可以透過向汽車新增顏色使其看起來更逼真。我們可以使用 fillcolor() 和 begin_fill() 方法用特定的顏色填充汽車。我們還可以使用 pencolor() 方法更改用於繪製汽車的筆的顏色。
t.fillcolor("red") t.begin_fill() # Draw the body of the car # ... t.end_fill() t.fillcolor("black") t.begin_fill() # Draw the wheels of the car # ... t.end_fill() t.pencolor("white") # Draw the windows and headlights of the car # ...
步驟 6:完成汽車
我們可以使用 hideturtle() 方法隱藏 turtle,並使用 done() 方法使視窗保持開啟狀態,直到使用者關閉它。
t.hideturtle() turtle.done()
以下是使用 Python 的 Turtle 繪製汽車的完整程式碼
import turtle # Create a Turtle object t = turtle.Turtle() # Draw the body of the car t.penup() t.goto(0, 50) t.pendown() t.goto(0, 100) t.penup() t.goto(0, 50) t.pendown() t.goto(75, 50) t.goto(100, 75) t.penup() t.goto(0, 100) t.pendown() t.goto(75, 100) t.goto(100, 75) # Draw the wheels of the car t.penup() t.goto(25, 25) t.pendown() t.circle(25) t.penup() t.goto(75, 25) t.pendown() t.circle(25) # Draw the windows and headlights of the car t.penup() t.goto(15, 100) t.pendown() t.goto(60, 100) t.goto(75, 75) t.goto(60, 50) t.goto(15, 50) t.goto(0, 75) t.goto(15, 100) t.penup() t.goto(90, 75) t.dot(10) # Add color to the car t.fillcolor("red") t.begin_fill() t.penup() t.goto(0, 50) t.pendown() t.goto(0, 100) t.goto(75, 100) t.goto(100, 75) t.goto(75, 50) t.goto(0, 50) t.end_fill() t.fillcolor("black") t.begin_fill() t.penup() t.goto(25, 25) t.pendown() t.circle(25) t.penup() t.goto(75, 25) t.pendown() t.circle(25) t.end_fill() t.pencolor("white") # draw windows t.penup() t.goto(15, 50) t.pendown() t.goto(60, 50) t.penup() t.goto(15, 100) t.pendown() t.goto(60, 100) #hide the turtle t.hideturtle() turtle.done()
輸出
結論
Turtle 繪圖是一種簡單有趣的學習程式設計的方式,它是教授孩子們計算機科學的優秀工具。在本文中,我們向您展示瞭如何使用 Python 的 Turtle 繪製汽車。我們已經介紹了 Turtle 繪圖的基本概念,例如建立 Turtle 物件、移動 turtle、繪製形狀和新增顏色。有了這些知識,您可以使用 Python 的 Turtle 繪圖建立更復雜和更有趣的圖案。