I want to make a button in PyGame but when I look it up literally no code works and I am on the verge of eating sand. Please I just need a simple code to make a clickable button.
Asked
Active
Viewed 173 times
1 Answers
0
The basic idea of a button includes knowing the x, y, width and height of your (presumably) rectangular button.
What you're trying to do is figure out if you mouse is within the coordinates of where your button is located and if the left mouse button is being pressed.
Here is a generic button class for doing exactly that:
class Button:
def __init__(self, x, y, text, centre=True):
self.colour = (0, 0, 0)
self.text = text
self.text = pygame.font.SysFont("comicsansms", 30).render(text, 1, self.colour)
if centre:
self.x = int(x - self.text.get_width() // 2)
self.y = int(y - self.text.get_height() // 2)
else:
self.x = x
self.y = y
self.width = int(self.text.get_width())
self.height = int(self.text.get_height())
# draw method which displays the text and border of the button
def draw(self, win):
pygame.draw.rect(win, (255, 255, 255), (self.x, self.y, self.width, self.height), 2)
win.blit(self.text, (self.x, self.y))
# method which returns true when the mouse is over the button and false when it isn't
def is_over(self):
pos = pygame.mouse.get_pos()
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
# method for detecting whether or not the button has been pressed and returns true if it has
@staticmethod
def is_pressed():
mouse = pygame.mouse.get_pressed()
if mouse[0]:
return True
return False
Instantiate a new object of the button class like follows:
btn = Button(
x=0,
y=0,
text="Example text which will display in top left corner",
centre=False
)
This might help you out a bit, you might need to edit the class to suit your use case.

Rabbid76
- 202,892
- 27
- 131
- 174

Alexander Hunter
- 83
- 1
- 8
-
Where did you copy this code from? When copying code, add at least a reference to the source. – Rabbid76 Apr 10 '21 at 12:46
-
It's my own code from one of my own private repos – Alexander Hunter Apr 10 '21 at 12:49
-
At least the `is_over` function is form a tutorial. In any case, the code can be greatly simplified. Use [`pygame.Rect`](https://www.pygame.org/docs/ref/rect.html#pygame.Rect) objects and [`pygame.Rect.collidepoint`](https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint) . Center the button by stetting the `center` attribute. – Rabbid76 Apr 10 '21 at 12:57