pythonimageturtle-graphics

How to make a turtle's shape an image in Python?


I want to make a small game with my own image for the turtle's shape. I've put both the program and the image in the same directory. Whenever I run the code it says:


File "C:\Users\Nobody PC\Desktop\THE PROJECT.py", line 51, in p.shape('beara') File "C:\Users\Nobody\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 2777, in shape self.turtle._setshape(name) File "C:\Users\Nobody\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 2493, in _setshape if self._type == "polygon" == screen._shapes[shapeIndex]._type: AttributeError: 'str' object has no attribute '_type'


My code includes nothing about a string (I think):


import turtle as t
bear =  "bear.png"
p = t.Turtle()
t.register_shape('beara',bear)
t.bgcolor('black')
p.shape('beara')

I made it:

t.register_shape('beara',"bear.png")

but still had the same error.


Solution

  • In addition to using a PNG instead of a GIF, you're not invoking the turtle methods correctly. I'll force OOP syntax, instead of the function syntax you used, to make the method ownership clearer:

    from turtle import Turtle, Screen
    
    image = "bear.gif"
    
    screen = Screen()
    screen.bgcolor('black')
    screen.register_shape(image)
    
    turtle = Turtle(shape=image)
    
    # ...
    
    screen.mainloop()
    

    Note that when using images as cursors, the name of the file is the name of the shape, you don't define your own name for it (unlike polygons.)