在PyGame中更改矩形颜色

2024-04-19 08:14:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: 代码recttesteventgetifscreenpygame
1条回答
网友
1楼 · 发布于 2024-04-19 08:14:43

我复制了你的代码,我不确定你是如何得到错误的(我无法复制它)。如果您看到的是白色屏幕,这是因为您有一行:screen.fill((255, 255, 255)),它将整个屏幕填充为白色,清除您已经绘制的矩形

要解决这个问题,您应该在填充屏幕白色后绘制矩形。你可以通过写作来做到这一点

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

而不是

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

相关问题 更多 >