pygame.error: Couldn't open images/ship.bmp


  在《python編程:從入門到實踐》這本書中的《外星人入侵》的項目里有如下代碼:

 Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
import pygame
class Ship():
    
def __init__(self, screen):
        
"""初始化飛船並設置其初始位置"""
        self.screen = screen
        
# 加載飛船圖像並獲取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        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)

  運行時可能會出現錯誤:pygame.error: Couldn’t open images/ship.bmp

  將self.image = pygame.image.load(‘images/ship.bmp’)中的圖片路徑補全。(因為是Windows系統所以用反斜杠“\”) 
       然后在路徑前加一個 r 讀取圖片文件。具體代碼如下:

 Python Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
import pygame
class Ship():
    
def __init__(self, screen):
        
"""初始化飛船並設置其初始位置"""
        self.screen = screen
        
# 加載飛船圖像並獲取其外接矩形
        # self.image = pygame.image.load('images\ship.bmp')
        self.image = pygame.image.load(r'D:\ship.bmp')
        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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM