button in pygame
import pygame
import sys
pygame.init()
class Button(pygame.sprite.Sprite):
def __init__(self,x, y,width,height, color, hover_color, text_color, font, text):
super().__init__()
self.font = font
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.original_color = color
self.hover_color = hover_color
self.text = text
self.text_color = text_color
self.text_surface = font.render(self.text, True, self.text_color)
self.surface = pygame.Surface(self.width, self.height)
self.surface.fill(self.color)
self.rect = self.surface.get_rect()
self.rect.center = (self.x, self.y)
self.text_rect = self.text_surface.get_rect()
self.text_rect.center = self.rect.center
self.clicked = False
def update(self, isclicked):
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.color = self.hover_color
self.surface.fill(self.color)
self.clicked = True
else:
self.color = self.original_color
self.surface.fill(self.color)
def draw(self, screen):
screen.blit(self.surface, self.rect)
screen.blit(self.text_surface, self.text_rect)
size = (800, 600)
screen = pygame.display.set_mode(size)
font = pygame.font.SysFont(None, 32)
btn = Button(100, 100, 100, 100, (0, 0, 0), (200, 200, 200), (255, 255, 255), font, 'Hello')
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
btn.update(True)
else:
btn.update(False)
screen.fill((255, 0, 0))
btn.draw()
pygame.display.update()
clock.tick(60)