turtle.pen() function in Python

The turtle.pen() function sets or returns the pen’s attributes (a “pen dictionary”) in a single command, including color, width, and speed.

Syntax: turtle.pen(pen=None, **pendict)
Parameters: Can be called with keyword arguments like turtle.pen(fillcolor=”red”, pencolor=”blue”, pensize=5).

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

Demo22.py

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

import turtle

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

# Get current pen settings
pen_settings = t.pen()
print("Pen settings:", pen_settings)

# Set multiple pen properties at once
t.pen(pencolor="red", fillcolor="blue", pensize=5)

window.exitonclick()

The following is the output:

turtle.pen() 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. Get pen settings: pen_settings = t.pen() returns a dictionary of current pen-related properties (e.g., pencolor, fillcolor, pensize, speed, pendown, shown).
  5. Print settings: print(“Pen settings:”, pen_settings) outputs that dictionary so you can see the current configuration.
  6. Set multiple properties: t.pen(pencolor=”red”, fillcolor=”blue”, pensize=5) updates several pen attributes at once. Future strokes will draw with a red outline, blue fill, and a line thickness of 5 pixels.
  7. Notes on equivalence: pensize is equivalent to width(); pencolor/fillcolor affect drawing only when the turtle moves or you use fill operations.
  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.width() function in Python
turtle.write() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment