使用 Turtle 在Python中绘制 Cube 和 Cuboid
先决条件:海龟编程基础
Turtle是Python中的一个内置模块。它使用屏幕(纸板)和海龟(笔)提供绘图。要在屏幕上绘制一些东西,我们需要移动海龟(笔)。要移动海龟,有一些函数,即 forward()、backward() 等。
绘图立方体
使用以下步骤:
- 先画前面的正方形
- 通过左下角移动到后方块
- 画出后面的正方形
- 如代码所示绘制剩余的一面。
下面是实现。
Python3
#import the turtle modules
import turtle
# Forming the window screen
tut = turtle.Screen()
# background color green
tut.bgcolor("green")
# window title Turtle
tut.title("Turtle")
my_pen = turtle.Turtle()
# object color
my_pen.color("orange")
tut = turtle.Screen()
# forming front square face
for i in range(4):
my_pen.forward(100)
my_pen.left(90)
# bottom left side
my_pen.goto(50,50)
# forming back square face
for i in range(4):
my_pen.forward(100)
my_pen.left(90)
# bottom right side
my_pen.goto(150,50)
my_pen.goto(100,0)
# top right side
my_pen.goto(100,100)
my_pen.goto(150,150)
# top left side
my_pen.goto(50,150)
my_pen.goto(0,100)
Python3
#import the turtle modules
import turtle
# Forming the window screen
tut = turtle.Screen()
# background color green
tut.bgcolor("green")
# window title Turtle
tut.title("Turtle")
my_pen = turtle.Turtle()
# object color
my_pen.color("orange")
tut=turtle.Screen()
# forming front rectangle face
for i in range(2):
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(150)
my_pen.left(90)
# bottom left side
my_pen.goto(50,50)
# forming back rectangle face
for i in range(2):
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(150)
my_pen.left(90)
# bottom right side
my_pen.goto(150,50)
my_pen.goto(100,0)
# top right side
my_pen.goto(100,150)
my_pen.goto(150,200)
# top left side
my_pen.goto(50,200)
my_pen.goto(0,150)
输出 :
绘制长方体
使用以下步骤:
- 先画前面的矩形
- 通过左下角向后移动到矩形
- 绘制背面矩形
- 如代码所示绘制剩余的一面。
下面是实现。
Python3
#import the turtle modules
import turtle
# Forming the window screen
tut = turtle.Screen()
# background color green
tut.bgcolor("green")
# window title Turtle
tut.title("Turtle")
my_pen = turtle.Turtle()
# object color
my_pen.color("orange")
tut=turtle.Screen()
# forming front rectangle face
for i in range(2):
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(150)
my_pen.left(90)
# bottom left side
my_pen.goto(50,50)
# forming back rectangle face
for i in range(2):
my_pen.forward(100)
my_pen.left(90)
my_pen.forward(150)
my_pen.left(90)
# bottom right side
my_pen.goto(150,50)
my_pen.goto(100,0)
# top right side
my_pen.goto(100,150)
my_pen.goto(150,200)
# top left side
my_pen.goto(50,200)
my_pen.goto(0,150)
输出 :