Python 图像出现在屏幕上,但不随按键事件移动

Python 图像出现在屏幕上,但不随按键事件移动,python,pygame,Python,Pygame,图像出现在屏幕上,但我无法使用程序中的w、s、a、d键移动图像。我该如何解决这个问题 import pygame, sys from pygame.locals import * pygame.init() black = (0,0,0) spriteLoc = ('sprite.png') #backgroundLoc = ('background.png') clock = pygame.time.Clock() pygame.key.set_repeat(30,30) pygame.

图像出现在屏幕上,但我无法使用程序中的w、s、a、d键移动图像。我该如何解决这个问题

import pygame, sys
from pygame.locals import *

pygame.init()

black = (0,0,0)
spriteLoc = ('sprite.png')
#backgroundLoc = ('background.png')

clock = pygame.time.Clock()
pygame.key.set_repeat(30,30)
pygame.display.set_caption('Focus.')
screen = pygame.display.set_mode((800,600))
sprite = pygame.image.load(spriteLoc).convert_alpha()
#background = pygame.image.load(backgroundLoc).convert_alpha()
#bgx,bgy = (0,0)

class Player():
    def __init__(self,x,y,image):
        self.x = x
        self.y = y
        self.image = image
#        self.posx = posx
#        self.posy = posy

    def playerEvents(self):
        global posx
        global posy
        posx = 0
        posy = 0
        if event.type == KEYDOWN:
            if pygame.key == K_w:
                posy -= 5
            elif pygame.key == K_s:
                posy += 5
            elif pygame.key == K_a:
                posx -= 5
            elif pygame.key == K_d:
                posx += 5
        if event.type == KEYUP:
            if pygame.key == K_w:
                posy = 0
            elif pygame.key == K_s:
                posy = 0
            elif pygame.key == K_a:
                posx = 0
            elif pygame.key == K_d:
                posx = 0

        self.x = self.x + posx
        self.y = self.y + posy

        #screen.blit(background,(bgx,bgy))
        screen.blit(self.image,(self.x, self.y))

me = Player(50,50,sprite)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        screen.fill(black)

        me.playerEvents()
        clock.tick(60)
        pygame.display.flip()

当我将posx和posy全局设置为正值并按下任意键或将鼠标移到窗口上时,精灵向右下移。使它们成为负数会使它们朝相反的方向移动。正如您从注释掉的代码中所看到的,我尝试使用背景图像来查看这是否产生了影响。我已经搜索、研究、注释出可能存在的问题区域,并重新安排了一切。我感谢你的帮助

您应该在
playerEvents
方法中将
pygame.key
更改为
event.key

您是否尝试过event.key而不是pygame.key让我知道这是否有效,我将作为答案提交。成功了!非常感谢。