Pygame graphics error: Couldn't open blue.png - python

I've been learning graphics in Pygame, and I tried to blit the background, but when I ran my program, it gave me this error:
pygame.error: Couldn't open blue.png
the png and the python file are in the same folder on my desktop.
My code is shown below:
from os import path
background = pygame.image.load('blue.png')
background_rect = background.get_rect()
screen.blit(background, background_rect)
screen.blit(background, background_rect)
all_sprites.draw(screen)
pygame.display.flip()
screen.fill(BLACK)

this doesn't work because 'blue.png' is simply a string; you must use path.join("NAME OF BASE DIRECTORY", "blue.png"). this will tell pygame where to look for a file with a name "blue.png". there are a few ways that you can make this run faster: call pygame.image.load(path.join("BASE DIR", "blue.png")).convert() this puts the image in the same format as the window making rendering much faster, you are blitting to the screen twice which is pointless and slows time, and if you aren't using OpenGL just use pygame.update() as it is slightly faster.

Related

pygame.error: File is not a Windows BMP file on m1 Mac running Mac os Monteray

I've looked around but haven't found any solutions that work.
I'm just learning pygame using the tutorial: https://www.youtube.com/watch?v=jO6qQDNa2UY&list=WL&index=44&t=1379s
but when I try to link the image I get the error: pygame.error: File is not a Windows BMP file.
I've tried everything short of reinstalling pygame again (previous issue), or reinstalling python.
Here is my code
import pygame
import os
pygame.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game")
WHITE = (255,255,255)
RED = (255,0,0)
FPS = 60
YELLOW_SPACESHIP_IMAGE = pygame.image.load(
os.path.join('Assets', 'spaceship_yellow.png')).convert()
RED_SPACESHIP_IMAGE = pygame.image.load(
os.path.join('Assets', 'spaceship_red.png')).convert()
def draw_window():
WIN.fill((RED))
WIN.blit(YELLOW_SPACESHIP_IMAGE, (300,100))
pygame.display.update()
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_window()
pygame.QUIT()
if __name__ == "__main__":
main()
You try to load spaceship_yellow.png and spaceship_red.png which judging from extensions are PNGs not BMPs, your error
pygame.error: File is not a Windows BMP file
suggest that pygame is expecting BMP file. pygame.image docs says
The image module is a required dependency of pygame, but it only
optionally supports any extended file formats. By default it can only
load uncompressed BMP images. When built with full image support, the
pygame.image.load() function can support the following formats.
then enumarate formats, apparently you do not have full image support, I think simplest solution is to convert PNGs you have to uncompressed BMP image format.
Turning the image to a BMP does work but I would rather still have the full functionality of pygame. What I did to finally make it work was from a thread here. I put this in the terminal to get it working:
python3 -m pip install git+https://github.com/nelsonlove/pygame.git
This will update your pygame to version 2.0.2.dev1, modified for m1 Mac.

Why does my pygame window not fit in my 4k(3840x2160) monitor? scale of pygame window: (3000x1500)

So I was trying to make a game with python and pygame but I noticed that I couldn't make a high resolution display because when I tried to make a display with more pixels, the pygame window was too big for my 4k (3840x2160) monitor. I should note that my monitor is connected to an old Dell laptop with a resolution of (1366x768). But when I entered this: print(pygame.display.list_modes()) it told me that I could use resolutions up to 4k and not just up to the resolution of my laptop. After a lot of searching and trying I accepted the fact that my game will be low resolution and moved on. As I continued coding the game I wanted to have a pop-up window so I imported pyautogui and my pygame window suddenly became much smaller. BOOM problem solved. I increased the resolution and I had no problems, my game was now running at a very high resolution! I was very confused so I made a very simple pygame program so I could test this and it actually worked. This is low quality and can't fit in my screen:
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((3000, 1500))
font = pygame.font.Font('font.otf', 50)
while True:
screen.fill((255, 255, 255))
txt = font.render("hello", True, (0, 0, 0))
screen.blit(txt, (100, 100))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screenshot1
And this is high resolution and does fit in my screen:
import pygame
import sys
import pyautogui
pygame.init()
screen = pygame.display.set_mode((3000, 1500))
font = pygame.font.Font('font.otf', 50)
while True:
screen.fill((255, 255, 255))
txt = font.render("hello", True, (0, 0, 0))
screen.blit(txt, (100, 100))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screenshot2
I don't even need to use pyautogui!
Can someone explain this to me?
Thanks
After a bunch of source diving I believe I have found the solution: pyautogui imports pyscreeze for the functions center, grab, pixel, pixelMatchesColor, screenshot. On lines 63 to 71 of pyscreeze/__init__.py is the following:
if sys.platform == 'win32':
# On Windows, the monitor scaling can be set to something besides normal 100%.
# PyScreeze and Pillow needs to account for this to make accurate screenshots.
# TODO - How does macOS and Linux handle monitor scaling?
import ctypes
try:
ctypes.windll.user32.SetProcessDPIAware()
except AttributeError:
pass # Windows XP doesn't support monitor scaling, so just do nothing.
The above code calls SetProcessDPIAware, which is equivalent to the following:
System DPI aware. This window does not scale for DPI changes. It will query for the DPI once and use that value for the lifetime of the process. If the DPI changes, the process will not adjust to the new DPI value. It will be automatically scaled up or down by the system when the DPI changes from the system value.
If want to get the same effect without pyautogui you can just include the above call to SetProcessDPIAware in your code.

Only some pygame projects works after converted from .py to .exe [duplicate]

This question already has answers here:
How can I convert pygame to exe?
(6 answers)
Pygame2Exe Errors that I can't fix
(3 answers)
Closed 1 year ago.
I want to be able to convert .py to .exe for python 3 pygame 1.9.4 projects (on my Windows 10 computer), and I have successfully converted some files by using auto py to exe (one file, console based):
https://nitratine.net/blog/post/auto-py-to-exe/.
For example, I tried to convert the code that is quite far up on this site:
http://openbookproject.net/thinkcs/python/english3e/pygame.html. That is:
import pygame
def main():
""" Set up the game and run the main game loop """
pygame.init() # Prepare the pygame module for use
surface_sz = 480 # Desired physical surface size, in pixels.
# Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((surface_sz, surface_sz))
# Set up some data to describe a small rectangle and its color
small_rect = (300, 200, 150, 90)
some_color = (255, 0, 0) # A color is a mix of (Red, Green, Blue)
while True:
ev = pygame.event.poll() # Look for any event
if ev.type == pygame.QUIT: # Window close button clicked?
break # ... leave game loop
# Update your game objects and data structures here...
# We draw everything from scratch on each frame.
# So first fill everything with the background color
main_surface.fill((0, 200, 255))
# Overpaint a smaller rectangle on the main surface
main_surface.fill(some_color, small_rect)
# Now the surface is ready, tell pygame to display it!
pygame.display.flip()
pygame.quit() # Once we leave the loop, close the window.
main()
The .exe file ran as it should when opened. However, some programs that I write are only partially functioning after the conversion.
One such program would be:
import pygame as pg
def main():
pg.init()
pg.display.set_caption('Some Caption')
screen = pg.display.set_mode((640, 480))
afont = pg.font.SysFont("some_font", 32)
done=False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill(0)
sometext = afont.render("Amazing text"
.format(0, 0), True, (250,200,250))
screen.blit(sometext, (10, 50))
pg.display.flip()
if __name__.endswith('__main__'):
main()
pg.quit()
After converted to exe, when I open it, some text about pygame appears and also the screen that is meant to pop up, showing the caption which I've set ('Some Caption'). The screen which popped up is however black and closes after a while, not showing what it should. However, I did get my exe file without any errors (which I could see anyway in the Output of the GUI which I used for the conversion i.e. auto py to exe). So in search of solutions I found this website:
https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/.
There were alot about error messages and general information but the thing I saw about program that opens but not doing what it should before closing was:
The Terminal Just Opens and Closes But There Are No Errors If you
double click to run your Python script, what happens? Does it open and
close also? That means this tool has done it's job correctly and the
script is finishing just like it should.
You most likely think the output should stay visible because you are
always using IDLE or an IDE and that's what those tools do. Add a
statement like input() at the end of your script to block execution
and wait for you to press enter before closing.
This, is not the solution for my problem since my program works if I double click on the python script. However, I think that it has a good point i.e that there might be something in my code that do not handle the conversion well, which is probable since the code from http://openbookproject.net/thinkcs/python/english3e/pygame.html did work after being converted to .exe when the same method was used.
My question is therefore, what is it that make my code not work after the conversion from .py to .exe?, and in that case, in what way might it be fixable?. The knowledge of what works and not when it comes to the converting .py to .exe would enable more programs to function correctly when they are .exe.
Thank you

How to use pygame.surface.scroll()?

I just found out about pygame.surface.scroll() and what I understand from the pygame documents that scroll() is for moving surface without the need to rebuild the background again to cover the old surface, just like pygame.rect.move_ip() but for surfaces.
Anyway, I don't know how to use it and the examples in the pygame documents are hard to me to understand as long as I am beginner and, after searching for long time, I couldn't found anything useful to understand how to use it.
Here is my code.
import pygame
from pygame.locals import*
screen=pygame.display.set_mode((1250,720))
pygame.init()
clock=pygame.time.Clock()
boxx=200
boxy=200
image = pygame.Surface([20,20]).convert_alpha()
image.fill((255,255,255))
while True :
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type==pygame.QUIT :
pygame.quit()
quit()
image.scroll(10,10)
screen.blit(image,(boxx,boxy))
pygame.display.update()
clock.tick(60)
EDIT: Your image and screen variables are backwards. That is also causing you some confusion I'm sure..
Your problem may is that you are trying to scroll an all black background. It is probably scrolling, and you just don't know it because the white box you used blit() to draw on the screen is stationary.
Try using something you can see scroll, like an image file. If you wanna move the white box, you can add a counter as a speed variable. Read this, then run it.
import pygame
from pygame.locals import*
screen=pygame.display.set_mode((1250,720))
pygame.init()
clock=pygame.time.Clock()
boxx=200
boxy=200
image = pygame.Surface([20,20]).convert_alpha()
image.fill((255,255,255))
speed = 5 # larger values will move objects faster
while True :
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type==pygame.QUIT :
pygame.quit()
quit()
image.scroll(10,10)
# I did modulus 720, the surface width, so it doesn't go off screen
screen.blit(image,((boxx + speed) % 720, (boxy + speed) % 720))
pygame.display.update()
clock.tick(60)
I can't say for sure the scroll function is working or not, learn to use an image as your background so you can see it moving first.

Pygame display.info giving wrong resolution size

I'm building a small game with pygame. I want the window of the game to be size of the monitors resolution. My computers screen's resolution is 1920x1080 and display.info says the window size is also 1920x1080 but when I run it, it creates a window roughly one and half times the size of my screen.
import pygame, sys
def main():
#set up pygame, main clock
pygame.init()
clock = pygame.time.Clock()
#creates an object with the computers display information
#current_h, current_w gives the monitors height and width
displayInfo = pygame.display.Info()
#set up the window
windowWidth = displayInfo.current_w
windowHeight = displayInfo.current_h
window = pygame.display.set_mode ((windowWidth, windowHeight), 0, 32)
pygame.display.set_caption('game')
#gameLoop
while True:
window.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#draw the window onto the screen
pygame.display.flip()
clock.tick(60)
main()
I've been having the same problem, and I managed to find the answer and posted it here. The answer I found is as follows:
I managed to find a commit on the Pygame BitBucket page here that explains the issue and gives an example on how to fix it.
What is happening is that some display environments can be configured to stretch windows so they don't look small on high PPI (Pixels Per Inch) displays. This stretching is what causes displays on larger resolutions to display larger than they actually are.
They provide an example code on the page I linked to showing how to fix this issue.
They fix the issue by importing ctypes and calling this:
ctypes.windll.user32.SetProcessDPIAware()
They also express that this is a Windows only solution and is available within base Python since Python 2.4. Before that it will need to be installed.
With that said, to make this work, put this bit of code anywhere before pygame.display.set_mode()
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
#
# # # Anywhere Before
#
pygame.display.set_mode(resolution)
I hope this helps you and anyone else who finds they have this same issue.

Categories