turtle.pencolor() function in Python

The turtle.pencolor() function sets the color of the pen, which is the color of the lines drawn when the turtle moves.

Syntax: turtle.pencolor(*args)
Parameters: Can be a colorstring (e.g., “blue”) or an RGB tuple (e.g., (0.2, 0.8, 0.55)).

Let us see an example to implement the turtle.pencolor() function in Python:

Demo26.py

# turtle.pencolor() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

t.pencolor("red")       # Set pen color to red
t.forward(100)
t.pencolor("#00FF00")   # Set pen color to green using hex
t.forward(100)

window.exitonclick()

The following is the output:

turtle.pencolor() function in Python

In the above code, we followed the below steps:

  1. Import the module: import turtle loads Python’s turtle graphics library.
  2. Create the screen: window = turtle.Screen() opens the drawing window.
  3. Create the turtle: t = turtle.Turtle() creates the turtle (your pen).
  4. Set red pen color: t.pencolor(“red”) sets the outline (line) color to red for upcoming strokes.
  5. Draw first segment: t.forward(100) draws a 100-unit red line.
  6. Set hex pen color: t.pencolor(“#00FF00”) changes the pen color to green using a hex code string.
  7. Draw second segment: t.forward(100) draws a 100-unit green line. Previously drawn lines keep their original colors.
  8. Close on click: window.exitonclick() keeps the window open until you click, then closes.

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

turtle.fillcolor() function in Python
turtle.filling() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment