Reputation: 33
I want this rectangle to be highlighted when the mouse is over it and to change its colour when clicked on. I've managed to get it to stay highlighted but the change in colour after a click is just momentary. How do I get it to stay this way?
Here's my code:
import pygame, sys
from pygame.locals import *
FPS = 30
BGCOLOR = (3, 115, 46)
BEFORECLICK = (22, 22, 106)
AFTERCLICK = (200, 200, 200)
boardWidth = 500
boardHeight = 500
rectX = 150
rectY = 150
rectWidth = 200
rectHeight = 200
myRectangle = pygame.Rect(rectX, rectY, rectWidth, rectHeight)
def main():
global FPSCLOCK, DISPLAYSURF
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((boardWidth, boardHeight))
pygame.display.set_caption("Klikni, kar klikni.")
mousex = 0
mousey = 0
while True:
mouseClicked = False
DISPLAYSURF.fill(BGCOLOR)
pygame.draw.rect(DISPLAYSURF, BEFORECLICK, myRectangle)
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouseClicked = True
mouseOver = determine_mouseOver(mousex, mousey)
if mouseOver == True and mouseClicked == True:
pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle)
elif mouseOver == True and mouseClicked == False:
pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle, 3)
pygame.display.update()
FPSCLOCK.tick(30)
def determine_mouseOver(valx, valy):
if myRectangle.collidepoint(valx, valy):
return True
else:
return False
main()
Any help is greatly appreciated. Thanks!
Upvotes: 3
Views: 16679
Reputation: 20438
I'd probably do something like this: Define a variable that refers to the currently selected button color (e.g. button_color = BEFORECLICK
) and if the user presses the button, just change it to AFTERCLICK
. Then you can draw the rect and pass the current color in the main loop pygame.draw.rect(DISPLAYSURF, button_color, myRectangle)
.
# Current color of the button.
button_color = BEFORECLICK
mouseOver = False
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONUP:
if mouseOver:
# Change the current color if button was clicked.
button_color = AFTERCLICK
mouseOver = determine_mouseOver(mousex, mousey)
DISPLAYSURF.fill(BGCOLOR)
# Just draw the rect with the current button color.
pygame.draw.rect(DISPLAYSURF, button_color, myRectangle)
if mouseOver:
pygame.draw.rect(DISPLAYSURF, AFTERCLICK, myRectangle, 3)
pygame.display.update()
FPSCLOCK.tick(30)
Upvotes: 2