我可以点击我的按钮,它仍然激活?

I can click around my button and it still activates?

我制作了 2 个按钮并让它们在我单击它们时发送消息“开始”或“退出”,但是我可以单击它们的范围比实际按钮大,所以我可以在按钮周围单击它仍然有效。它还会在单击它们时同时发送这两条消息。我试过改变图片,但它仍然做同样的事情。我不知道我该怎么办?我是新手所以请帮助。

这是我的主要内容:

import pygame
import button

window_width, window_height = 1000, 650

win = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("My game!")

grey = (25, 25, 25)

FPS = 60

start_img = pygame.image.load("img/start_button.png")
exit_img = pygame.image.load("img/exit_button.png")

start_button = button.Button(250, 220, start_img, 1.2)
exit_button = button.Button(265, 350, exit_img, 1.2)

def draw_window():
    win.fill(grey)

def main():
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        draw_window()
        if start_button.draw_button(win):
            print("START")
        if exit_button.draw_button(win):
            print("EXIT")
        pygame.display.flip()

    pygame.quit()


if __name__ == "__main__":
main()

这是我的按钮:

import pygame

class Button:
    def __init__(self, x, y, image, scale):
    width = image.get_width()
    height = image.get_height()
    self.image = pygame.transform.scale(image, ((width * scale), (height * scale)))
    self.rect = self.image.get_rect()
    self.rect.topleft = (x, y)
    self.clicked = False

def draw_button(self, surface):
    action = False

pos = pygame.mouse.get_pos()

if self.rect.collidepoint(pos):
    if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
    self.clicked = True
    action = True

if pygame.mouse.get_pressed()[0] == 0:
        self.clicked = False 


surface.blit(self.image, (self.rect.x, self.rect.y))
return action

我不知道它可能是什么,请提供任何建议,我们将不胜感激。

你的代码没有问题,我测试过了。问题出在按钮图像上。可能你的图像有一个大的透明 area.You 可以通过使用 get_bounding_rect().
创建一个较小的命中矩形来弥补这一点 另见 How to get the correct dimensions for a pygame rectangle created from an image

import pygame

class Button:
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, ((width * scale), (height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False
        self.hit_rect = self.image.get_bounding_rect()
        self.hit_rect.x += x
        self.hit_rect.y += y

    def draw_button(self, surface):
        action = False
        pos = pygame.mouse.get_pos()

        if self.hit_rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False 


        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action