首页 > 解决方案 > 如何在pygame中插入url链接

问题描述

我可以在 Pygame 中添加链接吗?就像在 HTML 中一样;一旦它被点击,我们将被重定向到 URL。我有游戏“回合制战斗”-> https://www.pygame.org/project/5492/7939 我想在屏幕上的某处添加一个文本,并带有他们可以按下的链接。如果你想看代码你可以在创作者的 Github 页面上查看,它和我现在的游戏基本一样。-> https://github.com/russs123/Battle

标签: pythonhyperlinkpygame

解决方案


您所要做的就是检查鼠标按下事件是否发生在文本的矩形内。然后您可以使用webbrowser.open()在浏览器中打开链接。

示例代码:

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()

推荐阅读