在Python中使用Turtle图形绘制彩虹
Turtle是Python中的一个内建模块。它提供了
1.使用屏幕(纸板)绘图。
2.Turtle(笔)。
为了在屏幕上画东西,我们需要移动Turtle(笔),为了移动Turtle,有一些函数,如forward(), backward(),等等。
用Turtle图形绘制彩虹
在本节中,我们将讨论如何使用Turtle Graphics的两种不同方式来绘制彩虹。
步骤:
1.import Turtle。
2.设置屏幕
3.制作Turtle对象
4.定义用于绘图的颜色
5.循环画半圆,以180度的位置为方向。
示例 1:
# Import turtle package
import turtle
# Creating a turtle screen object
sc = turtle.Screen()
# Creating a turtle object(pen)
pen = turtle.Turtle()
# Defining a method to form a semicircle
# with a dynamic radius and color
def semi_circle(col, rad, val):
# Set the fill color of the semicircle
pen.color(col)
# Draw a circle
pen.circle(rad, -180)
# Move the turtle to air
pen.up()
# Move the turtle to a given position
pen.setpos(val, 0)
# Move the turtle to the ground
pen.down()
pen.right(180)
# Set the colors for drawing
col = ['violet', 'indigo', 'blue',
'green', 'yellow', 'orange', 'red']
# Setup the screen features
sc.setup(600, 600)
# Set the screen color to black
sc.bgcolor('black')
# Setup the turtle features
pen.right(90)
pen.width(10)
pen.speed(7)
# Loop to draw 7 semicircles
for i in range(7):
semi_circle(col[i], 10*(
i + 8), -10*(i + 1))
# Hide the turtle
pen.hideturtle()
输出:
示例 2:
import turtle
mypen= turtle.Turtle()
mypen.shape('turtle')
mypen.speed(10)
window= turtle.Screen()
window.bgcolor('white')
rainbow= ['red','orange','yellow','green','blue','indigo','violet']
size= 180
mypen.penup()
mypen.goto(0,-180)
for color in rainbow:
mypen.color(color)
mypen.fillcolor(color)
mypen.begin_fill()
mypen.circle(size)
mypen.end_fill()
size-=20
turtle.done()