text to screen

PyGame Buttons, part 2, making the buttons interactive

A button is no good if a user doesn't actually realize that it is a button. There are all sorts of ways to make buttons appear to be buttons. One of the more popular ways to alert a user to the interactive-ness of a button is to have the button change color when a mouse hovers over it. That's what we're going to do here. We can do this using very similar logic as we used in the previous videos to know when objects had collided, only this time we're looking to find out if the mouse collided with our object. Our new game_intro function:
def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
        largeText = pygame.font.Font('freesansbold.ttf',115)
        TextSurf, TextRect = text_objects("A bit Racey", largeText)
        TextRect.center = ((display_width/2),(display_height/2))
        gameDisplay.blit(TextSurf, TextRect)

        mouse = pygame.mouse.get_pos()


        if 150+100 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
            pygame.draw.rect(gameDisplay, bright_green,(150,450,100,50))
            pygame.draw.rect(gameDisplay, green,(150,450,100,50))
        pygame.draw.rect(gameDisplay, red,(550,450,100,50))

The additional code is asking if the mouse is within the boundaries of the rectangle. If it is, then we use a lighter color. This of course requires a regular green and a light green to be defined.

Here are my colors at the moment:

red = (200,0,0)
green = (0,200,0)

bright_red = (255,0,0)
bright_green = (0,255,0)

The next tutorial:

  • Introduction to PyGame
  • Displaying images with PyGame
  • Moving an image around in PyGame
  • Adding boundaries
  • Displaying text to PyGame screen
  • Drawing objects with PyGame
  • Crashing
  • PyGame Score
  • Drawing Objects and Shapes in PyGame
  • Creating a start menu
  • PyGame Buttons, part 1, drawing the rectangle
  • PyGame Buttons, part 2, making the buttons interactive
    You are currently here.
  • PyGame Buttons, part 3, adding text to the button
  • PyGame Buttons, part 4, creating a general PyGame button function
  • PyGame Buttons, part 5, running functions on a button click
  • Converting PyGame to an executable
  • Adding a pause function to our game and Game Over
  • PyGame Icon
  • Sounds and Music with PyGame