Skip to content
Advertisement

How can I make a button that goes to website in pygame?

I have a “Credits” menu in my pygame and I’d like to make some buttons that go to certain websites.

What I mean is, when the button is clicked, it should open up, for example, GitHub (or whatever the link is).

Is there a way I can achieve this?

Advertisement

Answer

Implement a Button class ans use the webbrowser module to open an URL

import webbrowser
if event.type == pygame.MOUSEBUTTONDOWN:
    if self.rect.collidepoint(event.pos) and event.button == 1:
        webbrowser.open(self.url)

See also Pygame mouse clicking detection and How can I open a website in my web browser using Python?


Minimal example:

import pygame
import webbrowser

class Button(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h, font, text, action):
        super().__init__() 
        text_surf = font.render(text, True, (0, 0, 0))
        self.button_image = pygame.Surface((w, h))
        self.button_image.fill((96, 96, 96))
        self.button_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        self.hover_image = pygame.Surface((w, h))
        self.hover_image.fill((96, 96, 96))
        self.hover_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        pygame.draw.rect(self.hover_image, (96, 196, 96), self.hover_image.get_rect(), 3)
        self.image = self.button_image
        self.rect = pygame.Rect(x, y, w, h)
        self.action = action

    def update(self, event_list):
        hover = self.rect.collidepoint(pygame.mouse.get_pos())
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if hover and event.button == 1:
                    self.action()
        self.image = self.hover_image if hover else self.button_image

pygame.init()
window = pygame.display.set_mode((500, 300))
clock = pygame.time.Clock()
font50 = pygame.font.SysFont(None, 50)

button1 = Button(50, 40, 200, 60, font50, "Pygame",
                 lambda : webbrowser.open('https://www.pygame.org/news'))
group = pygame.sprite.Group(button1)

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement