19 Sep 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:

In the above code, we followed the below steps:
- Import the module: import turtle loads Python’s turtle graphics library.
- Create the screen: window = turtle.Screen() opens the drawing window.
- Create the turtle: t = turtle.Turtle() creates the turtle (your pen).
- Set red pen color: t.pencolor(“red”) sets the outline (line) color to red for upcoming strokes.
- Draw first segment: t.forward(100) draws a 100-unit red line.
- Set hex pen color: t.pencolor(“#00FF00”) changes the pen color to green using a hex code string.
- Draw second segment: t.forward(100) draws a 100-unit green line. Previously drawn lines keep their original colors.
- 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:
- OpenCV Tutorial
- Python Tutorial
- NumPy Tutorial
- Pandas Tutorial
- Matplotlib Tutorial
- Generative AI Tutorial
- LangChain Tutorial
- RAG Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments