pythonpython-3.xturtle-graphicspython-turtlewhiteboard

Can we add shape in turtle.shape()?


I want to code whiteboard program so I want to change shape of turtle to pen. I wanna know Do we have something in turtle to add further - like pen - shape in turtle.shape()? and if we have it, how can we add it?


Solution

  • The key to adding a new turtle cursor shape is the screen method register_shape() (aka addshape()). You can define the new shape either using polygons (individual or multiple) or an image file (traditionally a *.GIF but more recently also *.PNG, depending on the underlying version of tkinter).

    Once a shape is registered, it can be used with the turtle shape() method to change the cursor to the new shape. Based on the turtle documentation:

    from turtle import Screen, Turtle
    
    screen = Screen()
    screen.register_shape("custom.gif")
    
    turtle = Turtle()
    turtle.shape("custom.gif")
    

    However, images don't rotate with the turtle. For that, you can define a polygon-based shape:

    screen.register_shape("right_triangle", ((-10, 10), (-10, -10), (10, -10)))
    
    turtle = Turtle()
    turtle.shape("right_triangle")
    

    Though the polygon image might not be oriented the way you expect so you may need to rotate your turtle or adjust your polygon coordinates.