简体   繁体   中英

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.

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.)

I don't think that turtle module accepts ,png as a shape you must use a gif image. in your code just replace the image with a gif image and hope it will work check this out ....

import turtle

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

screen.addshape('shap1.gif')


t.shape('shap1.gif')
screen.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM