[英]Changing Rect Colors in PyGame
I'm very new to pygame, and I'm trying to make something very basic.我是 pygame 的新手,我正在尝试制作一些非常基本的东西。 The code is supposed to change the color of a rectangle based on the mouse's X position.
该代码应该根据鼠标的 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.如果您看到白色屏幕,那是因为您有以下行:
screen.fill((255, 255, 255))
,它将整个屏幕填满白色,清除您已经绘制的矩形。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.