I\'m new to pygame and have been attempting to create a simple interface with some buttons. I can\'t get the button to change color when the mouse hovers over it.
I\'ve
There are a lot of problems with your code, and would like to suggest a less verbose way to code this using pygame.Rect instead of pygame.Sprite, as it does not require as much understanding of game design and is an inheritance-free approach.
Firstly we create the button class:
import pygame
import sys
class Button:
def __init__(self, rect, default_colour=(0,255,0), hovered_colour=(255,0,0), text="", font=None): #using default arguments
self.rect = pygame.Rect(rect)
self.default_colour = default_colour
self.hovered_colour = hovered_colour
self.font = font if font else pygame.font.Font(None, 20) #initialise/import font
self.text = self.font.render(text, True, (0,0,0)) #render text
def draw(self, surf, mouse_coords):
if self.hover(mouse_coords):
pygame.draw.rect(surf, self.hovered_colour, self.rect, 0)
else:
pygame.draw.rect(surf, self.default_colour, self.rect, 0)
surf.blit(self.text, self.text.get_rect(center=self.rect.center)) #rect has a centre attribute
def hover(self, mouse):
mouse_rect = pygame.Rect(mouse, [1,1]) #using inbuilt collision function
return mouse_rect.colliderect(self.rect) #returns a boolean, no need to do this: if mouse_rect.colliderect(self.rect): return True, else: return False
then we write the main program loop (continues on from previous block of code)
pygame.init()
screen = pygame.display.set_mode([500,500])
def response1(): #callback function when button 1 is pressed
print("Button 1 pressed")
def response2(): #callback function when button 2 is pressed
print("Button 2 pressed")
def main(buttons):
while True: #setting a variable to True is unnecessary as you can just use "break" to exit the loop.
#this is only not the case in rare cases
screen.fill((255,255,255)) #unneccessary to put in another function
for event in pygame.event.get(): #only 1 event loop required
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
for button in buttons:
if button["button"].hover(pygame.mouse.get_pos()):
button["func"]() #calls function if clicked on
for button in buttons: #draws all buttons in array, can be optimised to not occur when user clicks
button["button"].draw(screen, pygame.mouse.get_pos())
pygame.display.flip() #update the surface at the end of the loop instead of the beginning
#only use pygame.display.update(rect=None) to update a specific portion of the display, otherwise stick to flip()
if __name__ == "__main__": #if file is not a module
button1 = Button([130, 200, 90, 100], text="Press")
button2 = Button([280, 200, 90, 100], text="Me", default_colour=(255,255,0))
buttons = [ #array of dicts to store buttons and callback functions, for multiple buttons
{
"button": button1,
"func": response1
},
{
"button": button2,
"func": response2
}
]
main(buttons)