我是学习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 代码,结果很好;但这次我得到一个白色的屏幕窗口。我的代码有什么问题吗?感谢您的帮助!!
最佳答案
这需要我大量的调试才能修复,哈哈。
首先,您不会在任何 while
循环中进行转义或更新。一旦代码进入第一个 while
循环,此后就不会再更新任何内容(pygame.display
),从而导致白屏综合症。
此外,请一致地命名变量并检查代码中的拼写错误。您创建了一个 blueSquareVy
变量,只是为了稍后尝试将其引用为 blueSquareVY
,并且最后拼写错误了 pygame.display.update()
的代码。大小写很重要——这只是一些拼写错误!
代码中也存在逻辑错误。在图形绘制到屏幕上之后,您不应该填充窗口表面。看看你的变量,你似乎希望小方 block 移动。您可以在 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()
希望这有帮助!
关于python - 运行pygame代码,它显示 'Module ' pygame'没有 'init'成员'和白屏窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48851883/