How do I add textures to sprites?
I have a sprite called spriteName. Whenever I type something like.
self.spriteName.texture = ('plc:Gem_Blue')
or import my own image into my own folder called Textures and use
self.spriteName.texture = ('Textures/IMG_0469.JPG')
They both result in the error "TypeError: Expected a Texture Object"
I don't know what I'm doing wrong.
Okay now there's no error, but I can't see the sprite when the code compiles.
Here's my setup method
def setup(self): self.background_color = 'green' self.spriteName = SpriteNode() self.spriteName.anchor_point = (5,5) self.spriteName.position = (50, 50) self.spriteName.texture = Texture('plc:Gem_Blue')
You haven't added the sprite to the scene. You have to add something like
self.add_child(self.spriteName). Alternatively, you could also pass
That solves the issue with the blue gem not appearing, but if I use one of my own images that I imported into the folder
self.spriteName.texture = Texture('IMG_0469.JPG')
returns a "Image not found" error and
self.spriteName.texture = Texture(ui.Image.named('IMG_0469.JPG'))
returns a "Could not load image" error
Is the imported image in the same folder as your script?
Yes it is
@omz Does the folder have to have the same name as the program?
No, that's not necessary, but the image shouldn't be in a sub-folder (or you'd need to include the sub-folder's name in the image name).
It's not in a sub folder. I have no idea why it's not working.
import os print(os.listdir(os.curdir)) # see if 'IMG_0469.JPG' is in that list
from scene import * class MyScene (Scene): def setup(self): self.background_color = 'green' self.spriteName = SpriteNode() self.spriteName.position = self.size / 2 self.spriteName.texture = Texture('plc:Gem_Blue') #self.spriteName.texture = Texture('canvas.png') #self.spriteName.texture = Texture('image000.jpg') self.add_child(self.spriteName) run(MyScene())
import os print(os.path.abspath(os.curdir)) print(os.listdir('.'))
at the start of your script. Then, copy and paste the name of the image that gets printed to the console. A common problem is that this is case sensitive, you must type the name exactly as it is printed.
I did what you said but I'm still getting the "Image Not Found" Error
What was printed when you added @JonB and/or my code?!?
Does adding the following code print True or False?!?
import os print('IMG_0469.JPG' in os.listdir(os.curdir))