Python Forum
[PyGame] Importing a .png image
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Importing a .png image
#1
I am trying to create a class called Ship in a separate .py file and I am trying to import its associated .png image (ship.png) into my Pygame file and every time I try to import the image or the class I receive this error message:
Error:
Traceback (most recent call last): File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien invasion.py", line 28, in <module> run_game() File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\alien invasion.py", line 15, in run_game ship = Ship(screen) File "C:\Users\maxya\PycharmProjects\pygame\Alien Invasion\ship.py", line 4, in __init__ self.image = pygame.image.load('ship.png') NameError: name 'pygame' is not defined
The code for the separate .py file for the ship class is this:

class Ship():
    def __init__(self, screen):
        self.screen = screen
        self.image = pygame.image.load('ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

    def blitme(self):
        self.screen.blit(self.image, self.rect)
The source code for the file I am trying to import the ship image and class into is this:
Please note that there is another class called settings but I am sure that is not the cause of the problem since the program ran fine before with it in it.

import sys

import pygame

from alien_invasion_settings import Settings

from ship import Ship

def run_game():
   # init the game and create a screen object
   pygame.init()
   ai_settings = Settings()
   screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
   pygame.display.set_caption("Alien Invansion")
   ship = Ship(screen)

# main loop
   while True:
      for event in pygame.event.get():
         if event.type == pygame.QUIT:
            sys.exit()
        
      screen.fill(ai_settings.bg_color)
      ship.blitme()
      
      pygame.display.flip()
   
run_game()
Any help would be greatly appreciated and thank you so much for your time.

* All the files are saved in the exact same folder and the image is in a .png format.
Reply


Messages In This Thread
Importing a .png image - by Myang123 - Sep-15-2019, 01:42 AM
RE: Importing a .png image - by Larz60+ - Sep-15-2019, 01:44 AM
RE: Importing a .png image - by buran - Sep-15-2019, 03:23 AM
RE: Importing a .png image - by SheeppOSU - Sep-15-2019, 04:13 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020