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 managed to create the button, but cannot get it to interact with my mouse. The code create an button object with one instance of a green button. It should change the button from green to red when mouse hovers over.
import pygame
pygame.init()
display_width = 1200
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
StartScreen = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Log In')
clock = pygame.time.Clock()
StartScreen.fill(white)
class Buttons():
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = int(x)
self.y = int(y)
self.w = int(width)
self.h = int(height)
self.text = text
def Draw(self, StartScreen, outline=None):
if outline:
pygame.draw.rect(StartScreen, outline, (float(self.x-2), float(self.y-2), float(self.w+4), float(self.h+4)), 0)
pygame.draw.rect(StartScreen, self.color, (self.x, self.y, self.w, self.h), 0)
if self.text != '':
font = pygame.font.SysFont('comicsans', 20)
text = font.render(self.text, 1, black)
StartScreen.blit(text, (self.x + (self.w/2 - text.get_width()/2), self.y + (self.h/2 - text.get_height()/2)))
def MouseOver(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.w:
if pos[1] > self.y and pos[1] < self.y + self.h:
return True
return False
def redrawWindow():
StartScreen.fill(white)
GrnBut.Draw(StartScreen, black)
run = True
GrnBut = Buttons(green, 150, 200, 90, 100, 'Press')
while run:
redrawWindow()
pygame.display.update()
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
Exit = False
while not Exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print(event)
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if GrnBut.MouseOver(pos):
print("Clicked")
if event.type == pygame.MOUSEMOTION:
if GrnBut.MouseOver(pos):
GrnBut.color = red
else:
GrnBut.color = green