I’m having problem following this tutorial. After I run it, an error message pops up
«ball = pygame.image.load(«…) Error:File is not a Windows BMP file.
I’m on OSX 10.9.5
I highly suspect I messed up the installation for all the necessary components, and the my steps are the following when I install:
- Delete Python 3 and reinstall Python 2.7 32-bit version (using the .dmg)
- Install the pygame package using the .dmg
- Was asked to install X11, installed X11
- Open SDL framework .zip and drag and drop into a folder in Application/Library
Did I mess it up? Especially for the SDL? Please tell me the solution, thank you.
//Tried putting the image file in the same directory; saving the image file as .bmp
asked Jan 28, 2015 at 13:57
I followed the solution here answer. Head to Macintosh HD/Library/Frameworks/….. and delete the pygame folder within and reinstall.
answered Jan 28, 2015 at 15:06
LeonBrainLeonBrain
3271 gold badge3 silver badges15 bronze badges
1
I saw the link and save the pic as ball.bmp (the pic is a gif format in the page) and try the code below:
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
It works fine for me. Maybe you should save the pic as a .bmp file and try again.
answered Jan 28, 2015 at 14:04
lqhcpsgbllqhcpsgbl
3,6543 gold badges20 silver badges30 bronze badges
2
This was problematic for me (even for the latest version of Pygame currently 2.1.2
). I tried uninstalling and reinstalling in my pyenv virtualenv but that did not help. What ultimately helped was installing some additional system dependencies via homebrew.
$ brew install sdl2 sdl2_mixer sdl2_gfx sdl2_image sdl2_net sdl2_ttf
And after this, I uninstalled and reinstalled pygame via pip and it started working.
answered Jan 18 at 1:47
PaulMestPaulMest
11.6k6 gold badges51 silver badges49 bronze badges
Running:
Mac OSX mountain Lion 10.8.3
Python 2.7.2
Pygame 1.9.2
I have a simple python pygame program that displays an image on the screen, this works great when I run it in my IDE. The problem comes when try to make it a standalone program using py2app I get the Error:
pygame.error: File is not a Windows BMP file
I did some research and found out that it is probably an error with pygame or SDL_image.framework so I reinstalled both and I get the same error. However, when I do use a BMP image the program works fine although I cannot use image formats such as .png or .jpg.
window.py:
import pygame,sys
from pygame.locals import *
pygame.init()
size=[700,500]
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
img = pygame.image.load("Images/img.png") # Error generated here
# -------- Main Program Loop -----------
while True:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
for event in pygame.event.get():
if event.type == QUIT:
isRunning = False
pygame.quit()
sys.exit()
screen.blit(img,(300,300))
pygame.display.flip()
clock.tick(20)
If it is of any use, here is my setup.py file:
from setuptools import setup
APP = ['window.py']
DATA_FILES = [('', ['images'])]
OPTIONS = {'argv_emulation': True}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
Problem Solution for 2.7.2:
Turns out my pygame files got or were corrupted. To solve the problem I replaced my old pygame files within the application with new pygame files. The pygame folder in the application is located at «app.app/Contents/Resources/lib/python2.7/lib-dynload». Replace the old pygame folder with this one and hopefully it will work:
https://dl.dropboxusercontent.com/u/84011326/Youtube%20files/pygame.zip
Other Solution
I downloaded python version 2.7.5 for mac and this simply fixed all errors from not being able to load the pygame mixer to being able to load jpg and png images.
Environment:
You can get some of this info from the text that pops up in the console when you run a pygame program.
- Operating system Mac M1:
- Python version Python 3.9.1 :
- SDL version SDL 2.0.14:
- PyGame version 2.0.2.dev1:
Current behavior:
I just build Pygame use this command below in my arm m1 Mac, everything almost running no error in this machine
brew install sdl2 sdl2_gfx sdl2_image sdl2_mixer sdl2_net sdl2_ttf
git clone https://github.com/pygame/pygame.git
cd pygame
python setup.py -config -auto -sdl2
python setup.py install
but when I run my code, It report a error like can’t read .png
file, and then I convert this png file to bmp, It’s running success
Screenshots
Test code
If possible add a simple test program that shows the problem described in this report.
import pygame
pygame.image.load('chessboard.png')
Stack trace/error output/other error logs
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pygame.error: File is not a Windows BMP file
Я работал над игрой для тестирования скорости набора текста, основанной на Pygame. Я пытаюсь запустить код, но получаю сообщение об ошибке:
Traceback (most recent call last):
File "/Users/beatricecesonyte/Downloads/python-project-typing-speed-game/speed typing.py", line 170, in <module>
Game().run()
File "/Users/beatricecesonyte/Downloads/python-project-typing-speed-game/speed typing.py", line 30, in __init__
self.open_img = pygame.image.load('type-speed-open.png')
pygame.error: File is not a Windows BMP file
Вот мой код:
import pygame
from pygame.locals import *
import sys
import time
import random
#750 x 500
class Game:
def __init__(self):
self.w=750
self.h=500
self.reset=True
self.active = False
self.input_text=''
self.word = ''
self.time_start = 0
self.total_time = 0
self.accuracy = '0%'
self.results = 'Time:0 Accuracy:0 % Wpm:0 '
self.wpm = 0
self.end = False
self.HEAD_C = (255,213,102)
self.TEXT_C = (240,240,240)
self.RESULT_C = (255,70,70)
pygame.init()
self.open_img = pygame.image.load('type-speed-open.png')
self.open_img = pygame.transform.scale(self.open_img, (self.w,self.h))
self.bg = pygame.image.load('background.jpg')
self.bg = pygame.transform.scale(self.bg, (500,750))
self.screen = pygame.display.set_mode((self.w,self.h))
pygame.display.set_caption('Type Speed test')
def draw_text(self, screen, msg, y ,fsize, color):
font = pygame.font.Font(None, fsize)
text = font.render(msg, 1,color)
text_rect = text.get_rect(center=(self.w/2, y))
screen.blit(text, text_rect)
pygame.display.update()
def get_sentence(self):
f = open('sentences.txt').read()
sentences = f.split('n')
sentence = random.choice(sentences)
return sentence
def show_results(self, screen):
if(not self.end):
#Calculate time
self.total_time = time.time() - self.time_start
#Calculate accuracy
count = 0
for i,c in enumerate(self.word):
try:
if self.input_text[i] == c:
count += 1
except:
pass
self.accuracy = count/len(self.word)*100
#Calculate words per minute
self.wpm = len(self.input_text)*60/(5*self.total_time)
self.end = True
print(self.total_time)
self.results = 'Time:'+str(round(self.total_time)) +" secs Accuracy:"+ str(round(self.accuracy)) + "%" + ' Wpm: ' + str(round(self.wpm))
# draw icon image
self.time_img = pygame.image.load('icon.png')
self.time_img = pygame.transform.scale(self.time_img, (150,150))
#screen.blit(self.time_img, (80,320))
screen.blit(self.time_img, (self.w/2-75,self.h-140))
self.draw_text(screen,"Reset", self.h - 70, 26, (100,100,100))
print(self.results)
pygame.display.update()
def run(self):
self.reset_game()
self.running=True
while(self.running):
clock = pygame.time.Clock()
self.screen.fill((0,0,0), (50,250,650,50))
pygame.draw.rect(self.screen,self.HEAD_C, (50,250,650,50), 2)
# update the text of user input
self.draw_text(self.screen, self.input_text, 274, 26,(250,250,250))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
x,y = pygame.mouse.get_pos()
# position of input box
if(x>=50 and x<=650 and y>=250 and y<=300):
self.active = True
self.input_text = ''
self.time_start = time.time()
# position of reset box
if(x>=310 and x<=510 and y>=390 and self.end):
self.reset_game()
x,y = pygame.mouse.get_pos()
elif event.type == pygame.KEYDOWN:
if self.active and not self.end:
if event.key == pygame.K_RETURN:
print(self.input_text)
self.show_results(self.screen)
print(self.results)
self.draw_text(self.screen, self.results,350, 28, self.RESULT_C)
self.end = True
elif event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
try:
self.input_text += event.unicode
except:
pass
pygame.display.update()
clock.tick(60)
def reset_game(self):
self.screen.blit(self.open_img, (0,0))
pygame.display.update()
time.sleep(1)
self.reset=False
self.end = False
self.input_text=''
self.word = ''
self.time_start = 0
self.total_time = 0
self.wpm = 0
# Get random sentence
self.word = self.get_sentence()
if (not self.word): self.reset_game()
#drawing heading
self.screen.fill((0,0,0))
self.screen.blit(self.bg,(0,0))
msg = "Typing Speed Test"
self.draw_text(self.screen, msg,80, 80,self.HEAD_C)
# draw the rectangle for input box
pygame.draw.rect(self.screen,(255,192,25), (50,250,650,50), 2)
# draw the sentence string
self.draw_text(self.screen, self.word,200, 28,self.TEXT_C)
pygame.display.update()
Game().run()
Я попытался найти другие вопросы, основанные на этой ошибке, но, похоже, ничего не работает …
Я использую macOS Catalina, Python 3.8.5 и Pygame 1.9.6.
На данный момент я не профессионал в использовании Python, поэтому, пожалуйста, постарайтесь четко объяснить!
Спасибо!
-
Langner.Troy
- Posts: 1
- Joined: Sat Jan 30, 2021 1:02 am
problem with opening image in pygame
I have looked at everything I can find and still no answer, hoping maybe someone here can. Followed tutorial and started building a game. Have a window with a square that can jump and move left and right. I am trying to add an image in place of the block but when I run the program I get
Pygame.error image not windows bmp file.
I re-installed pygame.. Moved everything to new file.. Tried pulling image through full path..
I can click the image to open as it’s own project and VSCode opens it right up no problem. I can post my code if needed just let me know..
-
rpiMike
- Posts: 2256
- Joined: Fri Aug 10, 2012 12:38 pm
- Location: Cumbria, UK
Re: Pygame.error not windows bmp file.
Mon Mar 08, 2021 2:26 pm
Langner.Troy wrote: ↑
Mon Mar 08, 2021 4:16 am
I have looked at everything I can find and still no answer, hoping maybe someone here can. Followed tutorial and started building a game. Have a window with a square that can jump and move left and right. I am trying to add an image in place of the block but when I run the program I getPygame.error image not windows bmp file.
I re-installed pygame.. Moved everything to new file.. Tried pulling image through full path..
I can click the image to open as it’s own project and VSCode opens it right up no problem. I can post my code if needed just let me know..
What type is your image? Post your code or a simple example that duplicates the error. Link the image file too if possible.
-
B.Goode
- Posts: 14653
- Joined: Mon Sep 01, 2014 4:03 pm
- Location: UK
Re: Pygame.error not windows bmp file.
Mon Mar 08, 2021 3:23 pm
Langner.Troy wrote: ↑
Mon Mar 08, 2021 4:16 am
I have looked at everything I can find and still no answer, hoping maybe someone here can. Followed tutorial and started building a game. Have a window with a square that can jump and move left and right. I am trying to add an image in place of the block but when I run the program I getPygame.error image not windows bmp file.
I re-installed pygame.. Moved everything to new file.. Tried pulling image through full path..
I can click the image to open as it’s own project and VSCode opens it right up no problem. I can post my code if needed just let me know..
With my Crystal Ball turned up to 11, I predict that that image file you are trying to load is not a Windows BMP file.
Return to “Python”
There are many users with problem regarding loading pygame images, be it jpeg or png.
«File is not a Windows BMP file» — not really helpful in this case
As per pygame documentation, to check if extended image support was enabled you should do:
>>> print(pygame.image.get_extended()) 0
Zero means it isn’t, but in my case I knew it was enabled and if you don’t — it probably is.
Road to enlightenment
I’ve opened my Python3.3 installation site-packages dir (your path may vary): /usr/lib/python3.3/site-packages/pygame/
there was image.so
file which is a pygame.image
module inside python interpreter,
but what about other similar file — imageext.so
? Both use libpng and image.so
imports successfully.
So what happens if I try to import imageext?
Well, that happens:
>>> import pygame.imageext Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libpng15.so.15: cannot open shared object file: No such file or directory
Now, that is a core of this problem — libpng version has changed and pygame depends on older one.
How to fix
There are 3 ways i can think of:
Quick one — You could symlink expected patch to current libpng but its ugly way and may yield unpredictable results ™.
Somewhat good — You can downgrade system libpng version to match expected
Best one — Fix everything! Recompile things if your system allows it — I’m using Gentoo so it is the way I choose
So, for the best way:
On any distribution — to list libs depending on missing file run:
grep -R libpng15.so.15 /usr/lib/*
Command could yield something like that:
Plik binarny /usr/lib/libSDL_image-1.2.so.0 pasuje do wzorca Plik binarny /usr/lib/libSDL_image-1.2.so.0.8.4 pasuje do wzorca Plik binarny /usr/lib/libSDL_image.so pasuje do wzorca
The sdl-image package got broken, and pygame depends on it.
Now, we have to just reinstall/update sdl-image package and everything should work. To the next libpng update