在PyGame中更改矩形颜色

4

我对pygame非常陌生,正在尝试制作一些非常基础的东西。这段代码应该根据鼠标的X位置改变矩形的颜色。

问题在于矩形要么不显示,要么控制台会给出错误提示:

AttributeError: 'pygame.Rect' object has no attribute 'color'

这里是相关代码:

    mouseButtons = pygame.mouse.get_pos()
    test = pygame.draw.rect(screen, (255,0,0), rect1)
    if (mouseButtons[0] <= 100):
        color = (0, 255, 0)
    else:
        color = (255, 0, 0)
    test = pygame.draw.rect(screen, color, rect1)

这里是完整的代码:

import pygame
from pygame.locals import *

SIZE = 400, 400

pygame.init()
screen = pygame.display.set_mode(SIZE)

rect1 = Rect(100, 100, 200, 200)

def loop():
    mouseButtons = pygame.mouse.get_pos()
    test = pygame.draw.rect(screen, (255,0,0), rect1)
    if (mouseButtons[0] <= 100):
        color = (0, 255, 0)
    else:
        color = (255, 0, 0)
    test = pygame.draw.rect(screen, color, rect1)

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

    
    loop()
    screen.fill((255, 255, 255))
    pygame.display.flip()

pygame.quit()
1个回答

2

我复制了你的代码,但不确定你是怎样发现错误的(我无法重现)。如果你看到一个白屏,那是因为你有这一行:screen.fill((255, 255, 255)),它会将整个屏幕涂成白色,清除你已经画过的矩形。

为了解决这个问题,你应该在将屏幕涂成白色后再画矩形。你可以通过编写以下代码来实现:

screen.fill((255, 255, 255))
loop() 

替代

loop()
screen.fill((255,255,255))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接