Can I add a link into a Pygame? Like in HTML; once it was clicked, we will be redirected to the URL. I have the game 'Turn Based Battle' -> https://www.pygame.org/project/5492/7939 I want to add a text somewhere on the screen with the link they can press on. If you want to look at the code you can check on the Github page from the creator, it's basically the same like the game I have now. -> https://github.com/russs123/Battle
Asked
Active
Viewed 1,072 times
1 Answers
4
All you have to do is check if the mouse press event happened inside the text's rect. Then you can use webbrowser.open()
to open the link in a browser.
Sample Code:
import pygame
import webbrowser
pygame.init()
screen = pygame.display.set_mode((1000, 800))
link_font = pygame.font.SysFont('Consolas', 50)
link_color = (0, 0, 0)
running = True
while running:
screen.fill((255, 255, 255))
rect = screen.blit(link_font.render("Sample Link", True, link_color), (50, 50))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
if rect.collidepoint(pos):
webbrowser.open(r"https://stackoverflow.com/")
if rect.collidepoint(pygame.mouse.get_pos()):
link_color = (70, 29, 219)
else:
link_color = (0, 0, 0)
pygame.display.update()

Art
- 2,836
- 4
- 17
- 34
-
Thank you very much, it works. – Matthew De Schepper Aug 12 '21 at 17:38