Turtle colours: pencolor(), pensize() and bgcolor()
pencolor() sets the colour of the lines a turtle draws, pensize() sets how
thick they are, and bgcolor() colours the window behind them.
Colour names and hex codes
Give pencolor() a colour name in quote marks, such as "red", "orange" or
"dark green". A hex code such as "#0080ff" mixes red, green and blue,
each from 00 (none) to ff (full).
import turtle
t = turtle.Turtle()
t.pencolor("red")
t.forward(100)
t.left(90)
t.pencolor("#0080ff")
t.forward(100)
The new colour is used from that line on. Lines already drawn keep theirs.
Thicker lines with pensize()
pensize(width) sets the line width in pixels. It starts at 1.
import turtle
t = turtle.Turtle()
t.pensize(1)
t.forward(60)
t.pensize(5)
t.forward(60)
t.pensize(10)
t.forward(60)
Colour the window with bgcolor()
The background belongs to the window, not to a turtle. turtle.Screen() gives
you the window, and its bgcolor() sets the background colour.
import turtle
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.pencolor("yellow")
t.pensize(3)
t.forward(100)
Read the current colour and size
With nothing in the brackets, pencolor() and pensize() tell you the current
values.
import turtle
t = turtle.Turtle()
print(t.pencolor(), t.pensize())
t.pencolor("orange")
t.pensize(4)
print(t.pencolor(), t.pensize())
A new turtle draws black lines 1 pixel wide.
Note: A misspelt colour name stops the program with
TurtleGraphicsError: bad color string. color() sets the pen colour and the
fill colour together; see Filling shapes.
See also: Filling shapes, The turtle screen.
Your turn
Add two lines before the forward(): make the pen "green" and 6 pixels
wide.
import turtle
t = turtle.Turtle()
# add two lines: make the pen green and 6 wide
t.forward(100)
print(t.pencolor())
print(t.pensize())
Expected output
green
6