【问题标题】:How can I make a button that goes to website in pygame?如何在pygame中制作一个进入网站的按钮?
【发布时间】:2021-07-30 14:03:48
【问题描述】:

我的 pygame 中有一个“积分”菜单,我想制作一些可以访问某些网站的按钮。

我的意思是,当单击按钮时,它应该打开,例如 GitHub(或任何链接)。

有什么方法可以实现吗?

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/a/31715178/2681662
  • @Rabbid76 我知道怎么做一个按钮,我已经有那个课程了,我只是不知道怎么让它去网站。您的代码有帮助,非常感谢!
  • @MSH 之类的,谢谢你的帮助!

标签: python python-3.x pygame


【解决方案1】:

实现一个Button 类并使用webbrowser 模块打开一个URL

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

另见Pygame mouse clicking detectionHow can I open a website in my web browser using Python?


小例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多