[英]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.