HOW TO create a button in pygame

This project creates a button enclosed in a home screen that responds to mouse_over event, it contains an event management system, different images for mouse_over and mouse_out and can be extended to all types of events like on_release on_click.. but also the event mechanism can be extended to catch key events


  • Python 2.x
  • Pygame
  • MacOS
  • Obsever

You'll be expecting that creating a button with mouse events in pygame should be a drag and prop like feature, it seems that it's not. Actually you need some OOP and design patterns knowledge to implement it. I used Observer pattern, inheritance, composition, and other OOP techiques.

The overview for the POC is:
* a main screen class that will hold the background image, a button and every other widgets in it(other eventual buttons for eg.)
* a event broadcating class that will contain all sorts of events like onClick, onKeyPress, it will register/unregister events and trigger actions..
* a main program loop that will listen to actions like: press a key or a mouse button.


The class Diagram looks like this:

Free HTML5 Template by FreeHTML5.coClass diagram

  • The Broadcast is an event manager that stores all the events. It implements an Observer pattern. It can hold any type of events from onClick, onRelease.. The Broadcast object is separated from the rest of the objects for separating concerns, you can register/unregister on various events regarding the screens that you're in For eg: on main menu screen you'll need events like onClick/onRelsease, but on other screen maybe you'll use only the keyboard to play a game.
  • The MainScreen object holds all the widgets, the background and registers the buttons for the necessary actions. It has also the functionality to root the events and map them to specific actions, for eg. it maps the global on_click to play_button.on_click callback.
  • PlayButton is the actual button, it inherits ButtonBase with it's mouse_over functionality. For drawing the button itself I created SpriteSheet, a class with functionality to carv a subimage from a bigger image. This is written with the idea that we'll have a big png file with all images inside for on_mouse_over on_mouse_out and so on.

Message routing

This is how the routing of the messages works:

Free HTML5 Template by FreeHTML5.coClass diagram

Code sample

get the code

Get Started

If you need some guidance in engineering field or you're seeking for some help don't hesitate to write me.

Let's work together