简体   繁体   English

更改一个类,以便当鼠标悬停在它上面时,它会改变颜色 - Pygame

[英]Changing a class so that when the mouse hovers over it, it changes colour - Pygame

import pygame as pg
import sys
import time

# All pygame stuff under here
pg.init()

# Font definitions
backFont = pg.font.SysFont("monospace", 40)
titleFont = pg.font.SysFont("garamond", 100)
cipherFont = pg.font.SysFont("garamond", 50)
buttonFont = pg.font.SysFont("garamond", 25)
bigFont = pg.font.SysFont("garamond", 100)
Font = pg.font.SysFont(None, 32)
inputFont = pg.font.SysFont('consola', 35)
errorFont = pg.font.SysFont('tahoma', 20)
diagramFont = pg.font.SysFont('courier new', 25)

# Colour definitions
BackGray = pg.Color('gray60')
screenGray = pg.Color('gray80')
buttonGray1 = pg.Color('gray40')
buttonGray2 = pg.Color('gray50')
buttonGray3 = pg.Color('gray30')
textColour = pg.Color('navy')

# Screen size set
screen = pg.display.set_mode((800, 600))

# Clock initiated to allow regular typing speeds
clock = pg.time.Clock()

# Change button class so that when the mouse pos is sent through, changes colour ======================
class Button(pg.sprite.Sprite):
    def __init__(self, text, x, y, width, height, enabled):
        super().__init__()
        self.colour = buttonGray2
        self.image = pg.Surface((width, height))
        self.image.fill(buttonGray2)
        self.rect = self.image.get_rect()
        txt = buttonFont.render(text, True, textColour)
        txtRect = txt.get_rect(center=self.rect.center)
        self.image.blit(txt, txtRect)
        self.rect.topleft = x, y
        self.enabled = enabled

    def isPressed(self, event):
        if self.enabled == True:
            if event.type == pg.MOUSEBUTTONDOWN:
                # MOUSE... events have an event.pos attribute (the mouse position)
                # which you can pass to the collidepoint method of the rect.
                if self.rect.collidepoint(event.pos):
                    return True
        return False
    def HoveredOver(self,event):
        print("Ocurring")
        if event.type == pg.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                print("Hoveredover")
                self.colour = buttonGray1
            else:
                self.colour = buttonGray2

def FrontPage():
    # Back screen
    screen.fill(screenGray)

    # Button definition for continuing
    Continue = Button('Continue', 105, 455, 120, 50, True)
    buttonsGroup = pg.sprite.Group(Continue)

    # Pygane while loop for events
    while True:
        for event in pg.event.get():
            mouseX, mouseY = pg.mouse.get_pos()
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
            elif Continue.isPressed(event):
                print("Continue")
            Continue.HoveredOver(event)

        buttonsGroup.draw(screen)

        pg.display.flip()
        clock.tick(60)

FrontPage()

I have this class to define and create buttons in Pygame. 我有这个类在Pygame中定义和创建按钮。 At the moment, when the mouse hovers over the button, it does not change colour. 此时,当鼠标悬停在按钮上时,它不会改变颜色。 I attempted to add another method in the class, so that it changes colour, if the mouse is over the button. 我尝试在类中添加另一个方法,以便在鼠标悬停在按钮上时更改颜色。 However, when I run the HoveredOver method, it does not change the colour of the button. 但是,当我运行HoveredOver方法时,它不会更改按钮的颜色。

How can I make this method work to change the colour of the button? 如何使此方法能够改变按钮的颜色?

Thanks in advance! 提前致谢!

It's not enough to change the colour attribute of the sprite, you also have to change the image because pygame blits the image onto the screen when you call buttonsGroup.draw(screen) . 改变精灵的colour属性是不够的,你还必须更改image因为当你调用buttonsGroup.draw(screen)时,pygame会将图像buttonsGroup.draw(screen)到屏幕buttonsGroup.draw(screen)

I'd create the images in the __init__ method or pass them as arguments and then swap them by assigning the current image to self.image if the mouse hovers over the button. 我将在__init__方法中创建图像或将它们作为参数传递,然后通过将当前图像分配给self.image如果鼠标悬停在按钮上)来交换它们。

class Button(pg.sprite.Sprite):

    def __init__(self, text, x, y, width, height, enabled):
        super().__init__()
        self.colour = buttonGray2
        self.image = pg.Surface((width, height))
        self.image.fill(buttonGray2)
        self.image_normal = self.image  # Store a reference to the original image.
        # Create a separate hover image.
        self.image_hover = pg.Surface((width, height))
        self.image_hover.fill(buttonGray1)
        self.rect = self.image.get_rect()
        txt = buttonFont.render(text, True, textColour)
        txtRect = txt.get_rect(center=self.rect.center)
        self.image.blit(txt, txtRect)
        self.image_hover.blit(txt, txtRect)  # Blit the text onto the hover image.
        self.rect.topleft = x, y
        self.enabled = enabled

    def isPressed(self, event):
        if self.enabled == True:
            if event.type == pg.MOUSEBUTTONDOWN:
                # MOUSE... events have an event.pos attribute (the mouse position)
                # which you can pass to the collidepoint method of the rect.
                if self.rect.collidepoint(event.pos):
                    return True
        return False

    def HoveredOver(self, event):
        if event.type == pg.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                print("Hoveredover")
                # Swap the image.
                self.image = self.image_hover
            else:
                # Swap the image.
                self.image = self.image_normal

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检测鼠标是否悬停在按钮上? PyGame 按钮类在悬停时不显示文本或更改颜色 - How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover 当鼠标在游戏中徘徊时如何遮挡一个盒子? - How to shade a box when mouse hovers in pygame? 鼠标悬停在物体上时的音效? - Sound effect when mouse hovers over object? 如何在鼠标悬停在精灵上时为精灵添加边框,并在鼠标停止后将其删除? - How do I add a border to a sprite when the mouse hovers over it, and delete it after the mouse stops? Pygame 鼠标悬停检测 - Pygame mouse over detect 使用 QFileSystemModel 将鼠标悬停在此 QTreeView 中的项目上时如何打印文件路径 - How to print the file path when the mouse hovers over an item in this QTreeView with QFileSystemModel pygame检测鼠标光标在对象上 - pygame detecting mouse cursor over object screen.get_at():运行代码pygame时图像颜色发生变化 - screen.get_at(): colour of image changes whilst running code pygame Tkinter:如何创建一个在用户将鼠标悬停在其上时突出显示的输入框? - Tkinter: How do I create an entry box that highlights as a user hovers their mouse over it? 为什么这个 pygame 程序不起作用,所以当我将鼠标悬停在计算机屏幕上时它会变成蓝色? - Why is this pygame program not working so when I hover over the computer screen it turns blue?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM