【问题标题】:Changing Rect Colors in PyGame在 PyGame 中更改矩形颜色
【发布时间】:2020-09-20 02:04:03
【问题描述】:

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

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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

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

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

    而不是

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

    【讨论】:

      猜你喜欢
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多