Pygame:按键改变屏幕颜色

1 投票
1 回答
3038 浏览
提问于 2025-04-18 08:57

我刚接触pygame,想要通过按键来改变screen.fill的颜色。下面我会贴上我的代码,任何帮助或建议都非常感谢。

import pygame
from pygame.locals import *

red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
white = (255,255,255)

background_color = (0,0,0,)
(width, height) = (800, 600)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Color Test')
screen.fill(background_color)

pygame.display.flip()

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            background_color = white
            print('left pressed')
            pygame.display.update()

1 个回答

1

在你改变background_color的值之后,需要让整个屏幕都填满这个颜色。

...
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
        background_color = white
        print('left pressed')
        screen.fill(background_color) #<--- Here
        pygame.display.update
    ...

撰写回答