Python 键盘输入背景

Python 键盘输入背景,python,pygame,keyboard-events,Python,Pygame,Keyboard Events,我一直在pygame工作,我需要一些键盘输入帮助。我试着把如果按下a键,背景会变成红色。不幸的是,它不起作用 也许是因为我无意或犯了语法错误 import pygame pygame.init() white = (34,34,34) black=(0,0,0) red=(255,0,0) silver=(110,108,108) yellow=(193,206,104) yellow2=(213,230,100) gameDisplay = pygame.display.set_mode((8

我一直在pygame工作,我需要一些键盘输入帮助。我试着把如果按下a键,背景会变成红色。不幸的是,它不起作用

也许是因为我无意或犯了语法错误

import pygame
pygame.init()
white = (34,34,34)
black=(0,0,0)
red=(255,0,0)
silver=(110,108,108)
yellow=(193,206,104)
yellow2=(213,230,100)
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('Slither')

gameExit=False

lead_x = 300
lead_y = 300

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x -= 10
                print("LEFT")

            if event.key == pygame.K_RIGHT:
                lead_x +=10
                print("RIGHT")
            if event.key == pygame.K_UP:
                 lead_y -=10
                 print("UP")
            if event.key == pygame.K_DOWN:
                 lead_y +=10
                 print("DOWN")
            if event.key == pygame.K_a:
                gameDisplay.fill(red)

    gameDisplay.fill(black)
    pygame.draw.rect(gameDisplay, white,[lead_x,lead_y,30,100])
    pygame.draw.ellipse(gameDisplay, white,[-35+lead_x,-54+lead_y,75,100])
    pygame.draw.ellipse(gameDisplay, red,[-25+lead_x,-35+lead_y,20,34])
    pygame.draw.ellipse(gameDisplay, red,[10+lead_x,-35+lead_y,20,34])
    pygame.draw.rect(gameDisplay, silver,[470+lead_x,-35+lead_y,75,30])
    pygame.draw.ellipse(gameDisplay, yellow,[400+lead_x,-35+lead_y,75,30])


    pygame.display.update()

pygame.quit()
quit()
您正在用红色填充屏幕,但一旦的
循环结束,您将在屏幕上绘制黑色,然后显示更新。与直接在
if
中校准
fill
不同,您可以使用新颜色更新
background\u color
变量,并在事件循环完成后将其用作填充颜色,从而使更改保持不变

#snip
background_color = black
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            #snip
            if event.key == pygame.K_a:
                background_color = red

    gameDisplay.fill(background_color)
    pygame.draw.rect(gameDisplay, white,[lead_x,lead_y,30,100])
    #snip