运行pygame代码时显示“模块'pygame'没有'init'成员”和白屏窗口
我刚开始学习Python,最近在调试从一本书上复制的一段代码时遇到了问题。我运行后只看到一个白色的窗口,而不是我期待的图案。以下是我的代码:
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
pygame.init()
windowWidth = 640
windowHeight = 480
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('Pygame Shapes!')
while True:
surface.fill((200, 0, 0))
pygame.draw.rect(surface, (255, 0, 0), (random.randint(0, windowWidth), random.randint(0, windowHeight), 10, 10))
greenSquareX = windowWidth / 2
greenSquareY = windowHeight / 2
while True:
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 255, 0),
(greenSquareX, greenSquareY, 10, 10))
greenSquareX += 1
# greenSquareY += 1
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX = 0.0
blueSquareY = 0.0
blueSquareVX = 1
blueSquareVy = 1
while True:
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX += blueSquareVX
blueSquareY += blueSquareVY
blueSquareVX += 0.1
blueSquareVY += 0.1
for event in GAME_EVENTS.GET():
if event.type == GAME_GLOBALS.QUIT:
pygame.quit()
sys.exit()
pygame.dispaly.update()
我遇到的第一个错误是:E1101:Module 'pygame' has no 'init' member'(4 ,1)
。之前我运行过其他使用pygame.init()
的Python代码,结果都很好;但这次却只出现了一个白色的窗口。我的代码哪里出错了呢?谢谢大家的帮助!!
相关问题:
- 暂无相关问题
1 个回答
4
这让我花了很多时间调试,哈哈。
首先,你在任何一个 while
循环中都没有进行更新或逃逸。一旦代码进入第一个 while
循环,之后就没有任何东西(比如 pygame.display
)会更新了,这就导致了你看到的白屏现象。
另外,请保持变量命名的一致性,并检查代码中的拼写错误。你创建了一个叫 blueSquareVy
的变量,但后来却试图用 blueSquareVY
来引用它,而且在代码的最后你拼错了 pygame.display.update()
。大小写是很重要的——这只是几个拼写错误而已!
代码中还有逻辑错误。你不应该在图形绘制到屏幕上之后再填充窗口表面。根据你的变量来看,你似乎想让小方块移动。你应该在 while
循环外创建位置变量,因为如果你在循环内创建它们,每次循环都会把它们重置为初始值。
这是经过注释和修复的代码:
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
pygame.init()
windowWidth = 640
windowHeight = 480
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('Pygame Shapes!')
# Renamed variables to be consistent
# Moved variables out of the while loop
greenSquareX = windowWidth / 2
greenSquareY = windowHeight / 2
blueSquareX = 0.0
blueSquareY = 0.0
blueSquareVX = 1
blueSquareVY = 1
# Joined the two while loops into one
while True:
surface.fill((200, 0, 0))
pygame.draw.rect(surface, (255, 0, 0), (random.randint(0, windowWidth), random.randint(0, windowHeight), 10, 10))
surface.fill((0, 0, 0))
pygame.draw.rect(surface, (0, 255, 0),
(greenSquareX, greenSquareY, 10, 10))
greenSquareX += 1
greenSquareY += 1
pygame.draw.rect(surface, (0, 0, 255),
(blueSquareX, blueSquareY, 10, 10))
blueSquareX += blueSquareVX
blueSquareY += blueSquareVY
blueSquareVX += 0.1
blueSquareVY += 0.1
# Do not capitalize the .get() method for pygame.event class
for event in GAME_EVENTS.get():
if event.type == GAME_GLOBALS.QUIT:
pygame.quit()
sys.exit()
# Misspelled pygame.display
pygame.display.update()
希望这对你有帮助!