I have a problem I'm working in Pycharm with Pygames and when I try to pygame.image.load() it doesn't work and keep telling me that it cannot find 'load' in image.py. I redownloaded the pygame package and it still doesn't work. Please help me.
Pycharm reports: Cannot find reference 'load' in 'image.py', when using pygame.image.load(). The code breaks when trying to execute this command.
import pygame
pygame.init()
surface = pygame.display.set_mode((1200, 720))
my_image = pygame.image.load('maxresdefault.bmp')
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
surface.fill((188, 22, 22)
surface.blit(my_image, (0, 0))
pygame.display.update()
pygame.quit()
After redownloading the Pygame package, the issue persists.
Code
Error text
PyCharm seems to have problems referencing load but it works fine. There are 2 separate issues here: The load error (which can be ignored as there doesn't seem to be any way around it, and PyGame works just fine), but secondly, and more importantly, there is a problem with your image file itself. Is it in the same directory as your script? .bmp is the standard format so that shouldn't be an issue. If it's in the right directory, and the name is correct, try converting it to a .png or .jpg image.
Related
Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes when I open the tab that it's in.
# I'm running Windows 10 with Spyder (Python 3.9), if that matters
# This is the entire code:
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Shooter Friends (Version 1.0)")
# Color presets
WHITE = (255,255,255)
BLACK = (0,0,0)
# Event loop
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.fill(WHITE)
pygame.display.update()
pygame.quit()
# Ensure the game only executes in the file named: space_shooter.py
if __name__ == "__space_shooter__":
main()
For context, I'm a beginner level student just trying to generate a basic white display for now, with dimensions: 9ooW x 500H, and centered ideally so that the pygame window's center is superimposed onto the center of my computer screen. I want this window to pop up as soon as the program starts running, and it should stay open for an indefinite amount of time, or until exited from with the X icon.
It seems to be producing the window right away as intended, but it places it into a minimized tab instead of an opened window display for some reason. The window pops open if I click on the tab, but it's filled in with black regardless of what values I insert into WIN.fill(R,B,G) as arguments. Also, the program immediately becomes non-responsive with the message: (Not responding) next to the game's title (at the top of the pygame window, not in the Spyder terminal).
Seems like it's not able to update for some reason, possibly causing it to crash, but I'm not really sure. I'm not getting any runtime or syntax errors from Python, but I do get a "Python is not responding" message from Windows in the pygame window as well as whenever I try to close the window using the X icon. Any help is much appreciated!
The problem is in the following line:
if __name__ == "__space_shooter__":
The __name__ variable will not contain the file name of the current script. If the script is ran directly, it will contain "__main__". If the script is imported by another script, it will contain the file name of that other script.
In order to check the script's file name, which you according to the comment wanted to do, you have to use the __file__ variable. The only problem is that the __file__ variable does not only containt the file name, but also the file path and the file extension. That's why I would use the str.endswith function, which checks whether a certain string ends with a given string. There are also some more complicate and reliable ways, but I will leave it to this:
if __file__.endswith("space_shooter.py"):
However, it is more common to check whether the current file is being ran directly instead of being imported from another file. This allows other files to import and use the functions and classes present in the file, without that everything in the file is ran too.
For this, you have to use the __name__ variable:
if __name__ == "__main__":
As said above, the __name__ variable will contain "__main__" when the file is ran directly. Thus we can compare __name__ with it to know whether the file is ran directly or not.
For more information on the __name__ variable, there is more explanation and a useful example.
This is my first time posting on Stack Overflow so please let me know if I could be doing anything better for asking my question!
Here is the tutorial I am following timestamped to about where I was. I am using VSCode Python, and Pygame. https://youtu.be/UZg49z76cLw?t=1138
I have the file in the directory specified and I have made sure it is named correctly by copy-pasting it.
Whenever I run my code, the bg_surface does not show up on my screen. Before it said that it didn't exist, but I have put the full file address in and it stopped doing that, but still won't display the actual image. I would also like to get away from using the full file path as I won't be able to send it...
import pygame, sys
pygame.init()#initiating pygame
screen = pygame.display.set_mode((576,1024))#Set canvas size
clock = pygame.time.Clock()
bg_surface = pygame.image.load('C:\\Users\\{my_name}\\MyPythonScripts\\Flapp\\assets\\background-day.png')
bg_surface = pygame.transform.scale2x(bg_surface)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()#Ends the game
sys.exit()#ends the program
screen.blit(bg_surface,(0,0))#Blit puts a surface on another surface
pygame.display.update#Update screen
clock.tick(120)#Set framerate
Things I have tried:
bg_surface = pygame.image.load('C:\\Users\\{my_name}\\MyPythonScripts\\Flapp\\assets\\background-day.png')
bg_surface = pygame.image.load('assets\\background-day.png')
bg_surface = pygame.image.load('assets/background-day.png')
bg_surface = pygame.image.load(r'assets/background-day.png')
bg_surface = pygame.image.load(r'assets\background-day.png')
bg_surface = pygame.image.load('assets\background-day.png')
And a lot of variations like those. Bonus points if you can tell me why I get:
Exception has occurred: SystemExit
File "C:\Users\Corbin\MyPythonScripts\Flapp\flapp.py", line 14, in <module>
sys.exit()#ends the program
When I close the program... Thanks!
Corbin, you haven't put parenthesis at the end of pygame.display.update. It should rather be pygame.display.update(). That's when you'll be able to get your background image.
I'm not able to add in images to my programme in Pycharm, I've imported Pygame and os and it wouldn't work. The image is in .png format 64 bit from flaticon.com
Is there something else I need to do to be able to add it in, I was following a PyGame tutorial online since I'm a beginner in programming
The python launcher just glitches when I add anything to do with an image. everything else works perfectly fine.
Here is the entire code of the project so far:
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Space Invaders - GAME ONE (PyGame)")
playerImg = pygame.image.load('space-invaders.png')
playerX = 370
playerY = 480
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
pygame.display.update()
this is the error message:
playerImg = pygame.image.load('space-invaders.png')
pygame.error: Couldn't open space-invaders.png
Process finished with exit code 1
it just glitches with any addition of an image. If I remove all image related code, it works fine
Also, import os just greys out in the editor
First check if the image is in the same folder as your .py. Next, make sure the image is really .png not just renamed for example, check this by trying to load another image. Last but not the least, check the spelling, maybe the name of the picture is misspelled. Since you are not using paths I can't remember anything else that could cause the issue.
Also, I do not know if it is the mistake during the copy process but last 2 lines of code need to be inside the for loop. And why you have imported os?
EDIT: Answer to the OP question in the comment
By importing os you can now use this module, nothing more. Here is how you can locate your .png file:
current_dir = os.path.dirname(__file__) #The location of your `.py`
img_dir = os.path.join(current_dir, "img_dir") #Path to the folder where your `png` is
player_img = pygame.image.load(os.path.join(img_dir, "space-invaders.png"))
Instead of "img_dir" you need to put the name of your folder, or the path, depending on the folder location.
I just installed Pygame 1.9.2 and am running Python 3.3. I'm having trouble figuring out how to make it so that when I click the 'X' in my pygame window, the program closes. I believe the following code works with Pygame 1.9.2 and Python 3.2, but is there any way to get it to work on Python 3.3? And what do I have to change to get the right effect? Here is some simple code that illustrates what I mean:
# Drawing Lines
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,500))
pygame.display.set_caption("Drawing Lines")
while True:
for event in pygame.event.get():
if event.type in (QUIT, KEYDOWN):
sys.exit()
screen.fill((0,0,200))
#draw the line
color = 255,255,0
width = 8
pygame.draw.line(screen, color, (100,100), (500,400), width)
pygame.display.update()
When I run this, a screen appears with a diagonal line on it, just like it's supposed to, but when I click the 'X' in the top-right corner of the window to close the window, I get the following error message:
Traceback (most recent call last):
File "C:\Python33\Exercise Programs\test_code\code\chap02\DrawingLines.py", line 13, in <module>
sys.exit()
NameError: name 'sys' is not defined
I guess the line that says sys.exit() is supposed to close the window if this is run in mython 3.2, but it isn't doing this in Python 3.3. The window just freezes and I get that error message. How do I achieve the desired effect in Python 3.3? What line do I need to enter?
Yo didn't import sys. Just add
import sys
to your imports, then it should work.
The fact that you see a window with the drawing at all suggests that the program is running fine otherwise.
The actual command used to close a project window is pygame.quit().
I'm using the code:
import pygame, sys, datetime
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen.fill((0, 0, 0, 255))
pygame.display.set_caption("TESTIFICATE")
if datetime.date.today().month == 12 and datetime.date.today().day == 25:
pygame.mixer.music.load("8bit-jingle-twist.mp3")
print("Merry Christmas!")
else:
pygame.mixer.music.load("timeless-mountains.mp3")
print("Loading Music...")
pygame.mixer.music.play(-1, 0.0)
print("Playing Background Music...")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Both 8bit-jingle-twist.mp3 and timeless-mountains.mp3 exist and can be played by VLC. My volume is on, as is my confusion.
Are you sure you are looking for them in the correct directory?
Try specifying the full path, ie
"c:/programs/mygame/music/8bit-jingle-twist.mp3"
Very strange, I simply copied your code and just changed the audio files to ones I had, and it worked perfectly fine.
I think therefore it has something to do with the files themselves.
It could be as Hugh Bothwell pointed out, the file path. In which case you could do three things:
Use the whole file path:
pygame.mixer.music.load("C:/blah/blah/blah/8bit-jingle-twist.mp3")
Use no file path (The file must then be in the same folder as the program)
pygame.mixer.music.load("8bit-jingle-twist.mp3")
Or use a one folder jump, where you have a folder inside the same folder as your program.
So for example you have your program in "My Documents", then you make another folder called "Music for Pygame" inside of "My Documents". Then the code would be:
pygame.mixer.music.load("Music for Pygame/8bit-jingle-twist.mp3")
I mostly use the last option, so that you can keep your files organized by having a folder for music, a folder for images, etc. and the program would still work if you moved the folder it was in.
Of course it could also be the audio file itself. Make sure it really is a .mp3 and that it plays fine (VLC is too awesome and can play anything, try playing it on Windows media or something just in case)
Also if using Windows 7 OS, try running it as an administrator and it might fix the problem.
(I ran the code on Windows XP and it worked fine just now)
NEW ANSWER:
if you saved your mp3 file as 'filename.mp3', and you wrote down the .mp3 file extension yourself, then the filename in pygame's pygame.mixer.music.load() function must be written as 'filename.mp3.mp3', because python expects you to add the .mp3. Sometimes the .mp3 is already included in the filename if you manually saved it as that.
Therefore, try this:
pygame.mixer.music.load('filename.mp3.mp3')