I want the image to not fade in but disappear in pygame

Viewed 24
import pygame, pygame_menu, sys, random

#Main Window
screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Classics")

#Variables
bg = pygame.image.load("bg.png")
pong_btn_img = pygame.image.load("Button2.png")
pong_btn_img_p = pygame.image.load("pongpressed.png")
default_img_size = (300, 195)
pong_btn_img = pygame.transform.scale(pong_btn_img, default_img_size)
pong_btn_img_p = pygame.transform.scale(pong_btn_img_p, default_img_size)

#General setup
pygame.init()
clock = pygame.time.Clock()


#BUtton Class
class Button():
    def __init__(self, x, y, image):
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
    def draw(self):
    
        # Get mouse pos
        pos= pygame.mouse.get_pos()
        #check mouse hover and click conditions
        if self.rect.collidepoint(pos):
            screen.blit(pong_btn_img_p, (self.rect.x, self.rect.y + 20))
            if pygame.mouse.get_pressed()[0]:
            exec(open("Game.py").read())
        else:
        #draw button on screen
            screen.blit(self.image, (self.rect.x, self.rect.y))

# button instances
pong_btn = Button(525, 300, pong_btn_img)

while True:

        #Handling Input
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    bg.set_alpha(20)
    screen.blit(bg, (0,0))
    pong_btn.draw()

    #Updating the screen
    pygame.display.flip()
    clock.tick(60)

In the function draw(), in the if else statement, Im displaying an image which displays when the mouse hovers over the image and a different image if the mouse is not hovering over. When the mouse goes from not hovering to hovering the image fades out and in. I want it to disappear immediately

1 Answers

[...] the image fades out and in. I want it to disappear immediately

Just remove the alpha blending with the background. Draw a solid background. Remove the line:

bg.set_alpha(20)


If you want the background to fade in at the beginning, you need to change the alpha channel of the background after a certain time respectively number of frames. The alpha channel of the background must be 20 for a certain time (e.g.: 1 second or 60 frames). After that, the background must be opaque and the alpha channel must be 255:

no_of_frames = 0
run = True
while run:    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    bg_alpha = 20 if no_of_frames < 60 else 255       
    bg.set_alpha(bg_alpha)

    screen.blit(bg, (0,0))
    pong_btn.draw()
    pygame.display.flip()
    clock.tick(60)
    no_of_frames += 1

pygame.quit()
sys.exit()
Related