簡體   English   中英

在 PyGame 中更改矩形 Colors

[英]Changing Rect Colors in PyGame

我是 pygame 的新手,我正在嘗試制作一些非常基本的東西。 該代碼應該根據鼠標的 X position 更改矩形的顏色。

問題是矩形要么沒有顯示,要么控制台給我一個錯誤:

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

我復制了你的代碼,但我不確定你是如何得到錯誤的(我無法重現)。 如果您看到白色屏幕,那是因為您有以下行: screen.fill((255, 255, 255)) ,它將整個屏幕填滿白色,清除您已經繪制的矩形。

要解決此問題,您應該在將屏幕填滿后繪制矩形。 你可以通過寫作來做到這一點

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

代替

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM