简体   繁体   中英

Changing Rect Colors in PyGame

I'm very new to pygame, and I'm trying to make something very basic. The code is supposed to change the color of a rectangle based on the mouse's X position.

The problem is that the rectangle either doesn't show up or the console gives me an error:

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

The code in question is here:

    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)

And here's the full code:

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

I copied your code, and I am not sure how you got the error (I couldn't reproduce it). If you are seeing a white screen, it is because you have this line: screen.fill((255, 255, 255)) , which fills the entire screen white, clearing the rectangles that you've already drawn.

To fix this, you should draw the rectangle after you fill the screen white. You can do that by writing

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

instead of

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM