Pygame - 按钮渲染的问题

时间:2017-12-04 20:10:42

标签: python pygame

基本上,我想创建一个按钮并用pygame在其上写文本,然后我就成功了。

但是当光标在按钮上时,最后一个按钮(名为leaderboardButton)不会将图像更改为“./image/mouseOnButton.png”。

我真的很想知道为什么会这样。按钮的其余部分没问题。

b

1 个答案:

答案 0 :(得分:2)

问题是由createButton方法第二行中的拼写引起的(使用pygame.Rect及其碰撞检测方法会更好):

if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
# Should be:
if((mouseX >= self.x and mouseX <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):

我建议您在while循环之前创建Button的实例,并为其提供drawhandle_event方法,以便您可以在其中调用button.draw(screen) while循环。我已经在以下示例中修改了Button。请注意,您可以使用pygame.Rect s作为blit位置和碰撞检测来简化代码。您还可以将按钮放入列表中并绘制它们并在for循环中处理事件,例如for button in button_list: button.draw(screen)

import sys
import pygame


pygame.init()
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))


class Button():
    def __init__(self, msg, font, x, y, w, h, color):
        self.msg = msg
        self.color = color
        self.font = pygame.font.SysFont(font, 32)
        self.text_surf = self.font.render(self.msg, True, self.color)
        self.image_normal = pygame.Surface((w, h))
        self.image_normal.fill(pygame.Color('dodgerblue1'))
        self.image_hover = pygame.Surface((w, h))
        self.image_hover.fill(pygame.Color('lightskyblue'))

        self.image = self.image_normal
        self.rect = self.image.get_rect(topleft=(x, y))
        # To center the text rect.
        self.text_rect = self.text_surf.get_rect(center=self.rect.center)

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                self.image = self.image_hover
            else:
                self.image = self.image_normal

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        screen.blit(self.text_surf, self.text_rect)


local_button = Button(
    "Local Play", "Comic Sans MS", 325, 200, 150, 75, (255, 255, 255))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        local_button.handle_event(event)

    screen.fill((30, 30, 30))
    local_button.draw(screen)

    pygame.display.update()
    clock.tick(FPS)