Turtle Colors and Filling Shapes Setting pen color and fill color. Filling shapes with colors. Using the color palette.
Setting Pen Color and Fill Color in Turtle Graphics
Turtle graphics in Python allows you to draw shapes and patterns easily. You can also set the pen color (the color of the lines) and the fill color (the color inside shapes). Here's how you can do it:
Setting the Pen Color
To set the pen color, use the pencolor() method. This method accepts color names (like "red", "blue", "green") or RGB tuples.
Example:
Python Code
import turtle
t = turtle.Turtle()
t.pencolor("blue") # Set pen color to blue
t.forward(100) # Draw a line 100 units long
Setting the Fill Color
To set the fill color, use the fillcolor() method. Similar to pencolor(), it accepts color names or RGB tuples.
Example:
Python Code
t.fillcolor("yellow") # Set fill color to yellow
Filling Shapes with Colors
To fill shapes, you need to start the filling process, draw the shape, and then end the filling process. Use the begin_fill() and end_fill() methods for this purpose.
Example:
Python Code
import turtle
t = turtle.Turtle()
t.pencolor("blue")
t.fillcolor("yellow")
t.begin_fill() # Start filling
t.circle(50) # Draw a circle with radius 50
t.end_fill() # End filling
Using the Color Palette
Turtle graphics provides a wide range of colors. You can also use RGB values to create custom colors.
Example using RGB values:
Python Code
import turtle
t = turtle.Turtle()
t.pencolor((0.5, 0.2, 0.8)) # Set pen color using RGB values
t.fillcolor((0.1, 0.7, 0.3)) # Set fill color using RGB values
t.begin_fill()
t.circle(50)
t.end_fill()
Complete Example with Multiple Shapes and Colors
Here is a complete example that demonstrates setting pen colors, fill colors, and filling different shapes with colors:
Python Code
import turtle
# Setup the screen
screen = turtle.Screen()
screen.bgcolor("lightblue")
# Create a turtle object
t = turtle.Turtle()
t.speed(3)
# Draw a red square
t.pencolor("red")
t.fillcolor("red")
t.begin_fill()
for _ in range(4):
t.forward(100)
t.right(90)
t.end_fill()
# Move the turtle to a new position
t.penup()
t.goto(150, 0)
t.pendown()
# Draw a green triangle
t.pencolor("green")
t.fillcolor("green")
t.begin_fill()
for _ in range(3):
t.forward(100)
t.left(120)
t.end_fill()
# Move the turtle to a new position
t.penup()
t.goto(-150, 0)
t.pendown()
# Draw a blue circle
t.pencolor("blue")
t.fillcolor("blue")
t.begin_fill()
t.circle(50)
t.end_fill()
# Hide the turtle
t.hideturtle()
# Keep the window open until it is closed by the user
turtle.done()
This example sets different pen and fill colors for three shapes: a square, a triangle, and a circle. It also demonstrates how to move the turtle to different positions without drawing lines (using penup() and pendown() methods).
Top of Form