Trying to get mouse position in my menu class

Good day!
I’m having trouble at the moment updating my mouse position. I have linked the menu class below, and it is called with:

menu = Menu(surf)
menu.run()

in the main file.
The issue is that when I try to hover over the “start button” to get it to change colour, it stays the same. A simple print(pygame.mouse.get_pos()) revealed that the mouse position doesnt change from when I first ran the program, so the box appears green if I start the program with my mouse on the box, and otherwise appears blue. Any help would be appreciated.

PS: this was made in a Team repl, which don’t support sharing, so I unfortunately can’t send the repl link.

import pygame
from settings import *

pygame.init()
pygame.font.init()
pygame.mixer.init()

music = pygame.mixer.Sound("Happy Holidays.mp3")
music.set_volume(0.3)
music.play(-1)

pygame.mouse.set_cursor(pygame.cursors.diamond)

clock = pygame.time.Clock()

class Menu():
  def __init__(self, surface):
    self.surf = surface
    self.bg = pygame.image.load("menu bg.png").convert()
    self.start_button = pygame.Rect(screen_width/2 - 50,screen_height * 2/3,100,50)
    self.font = pygame.font.SysFont('Arial', 30)

  def run(self):
    start_text = self.font.render('START', True, (231, 0, 13))
    
    while True:
      self.surf.blit(self.bg, (0, 0))
      mouse_pos = pygame.mouse.get_pos()
      print(pygame.mouse.get_pos())
      
      if self.start_button.collidepoint(mouse_pos):
        pygame.draw.rect(self.surf, "green", self.start_button)
      else:
        pygame.draw.rect(self.surf, "blue", self.start_button)
        
      self.surf.blit(start_text,(self.start_button.left + 5, self.start_button.top + 10))
      pygame.display.update()

      clock.tick(10) 

Try to include a loop to handle events in your run method

def run(self):
    start_text = self.font.render('START', True, (231, 0, 13))
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        self.surf.blit(self.bg, (0, 0))
        mouse_pos = pygame.mouse.get_pos()
        print(mouse_pos)
      
        if self.start_button.collidepoint(mouse_pos):
            pygame.draw.rect(self.surf, "green", self.start_button)
        else:
            pygame.draw.rect(self.surf, "blue", self.start_button)
        
        self.surf.blit(start_text, (self.start_button.left + 5, self.start_button.top + 10))
        pygame.display.update()

        clock.tick(10)

    pygame.quit()

The thing is, in a pygame application the events must be processing continuously so the application remains responsive.

Tell me if it works

1 Like