Loading images in pygame causes "pygame.error" - python

Whenever i try and run my pygame program in which I'm trying to load some images I always get plain "pygame.error" and nothing else.
I have imported pygame aswell as pygame.locals. At first i thought that it was because it couldnt find my files but whenever I change the name of a file to something thats incorrect it says "couldnt open image" so i guess that it really does find the file but fails when trying to load it. the startup() function is the first thing that is run from main. and i've also tried to do a simple grass=pygame.image.load('grass.png') with the grass.png file in the same directory as the python file
thankful for all the help i can get
..... line 41, in startup
surroundingsdict = {'gräs': pygame.image.load(os.path.join('images', 'grass.png')).convert_alpha(),
pygame.error
def startup():
pygame.init()
p1=Player.Player(int(random.random()*mapstorlek),int(random.random()*mapstorlek))
vh=ViewHandler.ViewHandler()
surroundingssdict = {'grass': pygame.image.load(os.path.join('images','grass.png')).convert(),
'mount': pygame.image.load(os.path.join('images', 'mount.png').convert)()}
playerdict={'p1': pygame.image.load(os.path.join('images','player.png')).convert()}

pygame.error is usually accompanied by a message with more details about what went wrong, like the 'couldn't open image' you get when you try a non-existant image. Are you sure you get no more info? Can't be sure what's wrong, but I'll throw out two suggestions:
Do you call pygame.display.set_mode to set a display surface before loading the images? You might be doing that in your ViewHandler class, but if not the convert() will fail since it changes the pixel format of the surface to match the display, which it of course can't do if there is no display active.
Another possibility is that you don't have full image support in pygame and can't load .png. Have you tried loading other formats? Try calling pygame.image.get_extended() to see if your pygame is built with extended image support. Even if it returns True there is no guarantee that you can load .png, but at least it's more likely to be something else.

Related

Why isn't my image being found in Pygame?

I was working on a space shooter game when I can across this problem:
File "C:\Users\willi\PycharmProjects\Pygame Testing\main.py", line 15, in <module>
icon = pygame.image.load("Images", "boss.png")
FileNotFoundError: No file 'Images' found in working directory 'C:\Users\willi\PycharmProjects\Pygame Testing'.
I am working in PyCharm where i created a directory called "Images" and I put all my icons and enemies. I wanted to put the boss as the icon but it didn't work. Please help me :(
There are two things to note here:
You do not need to specify the first parameter to be "Images". Just the path to the file will do (make sure that the path is relative to your current directory.) You can read up more about the pygame.image.load function here
PyGame sometimes tends to misbehave with normal variables. It is always a good idea to make them global in the main scope.
pygame.image.load takes in a filename as the first argument
'Images' is not a filename. Use icon = pygame.image.load("Images/boss.png")
(Read the docs here)

Pillow (PIL Fork): Error when using ImageFont/ImageDraw methods with custom font

After reading through much of the Pillow documentation, stack overflow, and the web, I have been unable to decipher this error message that is throwing off my application. My current setup:
Python 3.7.6
Pillow 7.0.0 [Docs]
Below is a verifiable example of what I have been working on. Essentially, my error happens when I use title_font in place of where I use default_font. Emphasized by the 2 comments stating: # TODO Aborts with error unless using default_font TODO.
from PIL import ImageFont, ImageDraw, Image
def app():
# Default Font with static size and font type
default_font = ImageFont.load_default()
# TODO Title Font that is the desired use
title_font = ImageFont.truetype(font="~/Library/Fonts/Verdana.ttf", size=36)
# Background Image to draw text on
bg_img = Image.new(mode = "RGBA",size = (3480,2160), color="Green")
# Creates an object that can be used to draw in the given image.
d = ImageDraw.Draw(bg_img)
txt = "Hello World"
# TODO: Aborts with error unless using default_font TODO
# Returns (width, height) of text in pixels with designated font
txt_width, txt_height = default_font.getsize(txt)
print(f"Text Width:{txt_width} Text Height: {txt_height}")
# TODO: Aborts with error unless using default_font TODO
# Draws "Hello World" onto background image
d.text((10,60), text=txt, font=default_font, fill=(255,255,255,255))
# Pop Up window
bg_img.show()
Below is the error message that I get back from both ImageDraw/ImageFont methods:
>>> app()
dyld: lazy symbol binding failed: Symbol not found: _hb_language_get_default
Referenced from: /usr/local/lib/libraqm.dylib
Expected in: flat namespace
dyld: Symbol not found: _hb_language_get_default
Referenced from: /usr/local/lib/libraqm.dylib
Expected in: flat namespace
I have already tried:
To change the path used for the custom font and to change to another font loading method (i.e. ImageFont.load(filename), ImageFont.load_path(filename).
To settle with ImageFont.load_default() but as you might be able to tell by running it, the default font is very small and there is no way of changing its size or style.
One last thing that I was not sure about was this line in the installation guide that recommended after brew install of the packages Pillow depends on:
Then see depends/install_raqm_cmake.sh to install libraqm.
Can be found here halfway through the Building on macOS section. I have a nagging feeling this could be the cause but I simply do not understand what action it wants me to take.
Long time lurker, first time poster. Thank you for any help now and all the help afforded to me over the years!
UPDATE: Used my example on another MacBook and it works fine. I am going to reset the one it wasn't working on and build from scratch. Thanks for all your assistance!
I assume you used (like me) a Mac with OS Catalina or similar, and might have installed the mentioned library with "$ brew install libraqm" too.
I resolved it by changing the layout_engine, and due to this, not using 'libraqm' for PIL layout work in the background.
font = ImageFont.truetype(
"/System/Library/Fonts/Keyboard.ttf", layout_engine=ImageFont.LAYOUT_BASIC, encoding=self.encoding, self.font_size,)
If you do this you might not be able to use Chinese or similar Fonts. I am not sure where, in 'brew', 'pyenv' or 'libraqm' is the issue but I try to find it out.

'image "pyimage2" doesn't exist'?

This is where the error is found:
global backbuttonimg
backbuttonimg = PhotoImage(file="backbutton.gif")
C6 = tkinter.Button(W_CheckDates, image=backbuttonimg, command = CheckDatesBack)
C6.pack()
I don't understand why this isn't working. I have another image in my program here:
def Login():
global W_Menu
W_Menu = Tk()
W_Menu.geometry('160x310+600+200')
W_Menu.title("NSS DB")
A0 = Canvas(W_Menu, width='160', height='160')
A0.pack()
global img
img = PhotoImage(file="nsslogo.gif")
A0.create_image(80,80, image=img)
I also get a similar error when I try to call the above definition after it has already been initially called (for example when my program logs out) so I have readjusted so the window simply deiconifies instead of calling it again, and I do not get the error again. However I am confused as to why I get an error with the former section of code now, as the button simply does not show up whether it is called for the first time or not. Sorry if this is a bit vague, please ask if I have not explained in enough detail. Thanks in advance.
P.S. I have looked in other threads with similar problems but none apply to me.
Ok so you say that the login function works once, then it can't work again. Here the problem can be solved using tk.Toplevel() instead of tk.Tk() see: why python photoimages don't exist? and tkinter.TclError: image "pyimage3" doesn't exist
These threads mention how you can't have two instances of Tk() running simultaneously, you have to use Toplevel() instead.
Why did these threads not apply to you (i think they do...)? But just a tip, if you state that they don't apply to you, then give reasons why, it helps make your question clearer. Also, add the full traceback when your question is about a particular error.
Hope this helps a bit.
Adding this for anyone who has tried the above with no success. If you have an erroneous path when running the script in some environments the path to the file is retained. I commented out everything from where I first use PhotoImage up to the window mainloop, run the script, close resulting gui, uncomment the code, run, and it shows the image as expected.
You can add a master parameter
backbuttonimg = PhotoImage(file="backbutton.gif",master=W_Menu)
Here Cledia
I am also facing this error.
And when I use Toplevel instead of To, it is working well
I suggest you to use TopleToplevel
Use tk.Toplevel() instead of tk.Tk() So its will work because the python coding library tkinter it doesnt make any sens if you make two windows working sametime with the tk.Tk() so you can use the toplevel() to open multiwindows in the same time !!
Hope it's Helpful

SimpleCV not responding after clicking the picture

I'm trying out SimpleCV and I'm noticing every time I click title bar, simplecv stops working to the pint that it crashes. Before crashing it says "pythonw.exe Stopped working." That happens if I edit my script and run it from the python idle. If I simply double click it, the image is displayed for 20secs and then just closes.
This is what I tried. Really simple.
from SimpleCV import Image
img = Image("carro.jpg")
img = img.scale(300,300)
img.show()
Just wondering if this could causes any kind of trouble while doing some image processing like subtracting colors and stuff like that.
Had the same problem and after searching found this: From http://help.simplecv.org/question/1118/why-imageshow-freezes/ it looks like it is caused by pyGame requiring a while loop to keep pumping events to the window.
The solution, as indicated at that post, and worked for me, was to use the quit() method on the window handle returned by show.
````
img = Image("carro.jpg")
img = img.scale(300,300)
win = img.show()
#wait for user input before closing
raw_input()
win.quit()
````

PyGTK set icon of window with stock image

I feel like this should be pretty simple, but I guess I am missing something.
So I want to set the icon of a window with one of the stock images. I have tried:
windowIcon = gtk.image_new_form_stock(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU)
window.set_icon(windowIcon.get_pixbuf())
Python then complains that:
File "./sample.py", line 44, in init
window.set_icon(windowIcon.get_pixbuf())
ValueError: image should be a GdkPixbuf or empty
I try to convert the gtkImage to a GdkPixbuf because when I didn't python complained that
TypeError: icon should be a GdkPixbuf or None
In the pygtk documentation it says:
If the storage type of the image is not either gtk.IMAGE_EMPTY or gtk.IMAGE_PIXBUF the ValueError exception will be raised.
So I guessing that storage type of the stock image is wrong. The question is how to I get around this?
You can use the .render_icon() method on any GtkWidget to provide a stock item as the icon.
windowicon = window.render_icon(gtk.STOCK_DIALOG_AUTHENTICATION, gtk.ICON_SIZE_MENU)
window.set_icon(windowicon)
The render_icon() method works as given above. Your code was having problems, because the get_pixbuf() method was returning None. This is because the image was not created from a pixbuf, and for some reason, it won't convert it. Another way of getting a pixbuf from an image is to use the gtk.gdk.pixbuf_new_from_image() function.

Categories