How to create a Button Class in pygame

Viewed 3643

I am new to Pygame and I have been trying to learn from a couple of sites but unfortunately, I am unable to figure it out how to make it.

I would appreciate it if you can help me, Thanks

2 Answers

Basically it depends on how complex you want it to be. I'm used to using this one from Tech with Tim: https://www.youtube.com/watch?v=4_9twnEduFA

class button():
def __init__(self, color, x,y,width,height, text=''):
    self.color = color
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.text = text

def draw(self,win,outline=None):
    #Call this method to draw the button on the screen
    if outline:
        pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
        
    pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
    
    if self.text != '':
        font = pygame.font.SysFont('comicsans', 60)
        text = font.render(self.text, 1, (0,0,0))
        win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

def isOver(self, pos):
    #Pos is the mouse position or a tuple of (x,y) coordinates
    if pos[0] > self.x and pos[0] < self.x + self.width:
        if pos[1] > self.y and pos[1] < self.y + self.height:
            return True
        
    return False

As you can see that's the code he implemented. It's enough for creating a button, giving it text and also having an action on click.

I think that it is all you need to start with the Pygame.

Try this code:

import pygame

class button:
    def __init__(self, position, size, clr=[100, 100, 100], cngclr=None, func=None, text='', font="Segoe Print", font_size=16, font_clr=[0, 0, 0]):
        self.clr    = clr
        self.size   = size
        self.func   = func
        self.surf   = pygame.Surface(size)
        self.rect   = self.surf.get_rect(center=position)

        if cngclr:
            self.cngclr = cngclr
        else:
            self.cngclr = clr

        if len(clr) == 4:
            self.surf.set_alpha(clr[3])


        self.font = pygame.font.SysFont(font, font_size)
        self.txt = text
        self.font_clr = font_clr
        self.txt_surf = self.font.render(self.txt, 1, self.font_clr)
        self.txt_rect = self.txt_surf.get_rect(center=[wh//2 for wh in self.size])

    def draw(self, screen):
        self.mouseover()

        self.surf.fill(self.curclr)
        self.surf.blit(self.txt_surf, self.txt_rect)
        screen.blit(self.surf, self.rect)

    def mouseover(self):
        self.curclr = self.clr
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            self.curclr = self.cngclr

    def call_back(self, *args):
        if self.func:
            return self.func(*args)

class text:
    def __init__(self, msg, position, clr=[100, 100, 100], font="Segoe Print", font_size=15, mid=False):
        self.position = position
        self.font = pygame.font.SysFont(font, font_size)
        self.txt_surf = self.font.render(msg, 1, clr)

        if len(clr) == 4:
            self.txt_surf.set_alpha(clr[3])

        if mid:
            self.position = self.txt_surf.get_rect(center=position)


    def draw(self, screen):
        screen.blit(self.txt_surf, self.position)




# call back functions
def fn1():
    print('button1')
def fn2():
    print('button2')


if __name__ == '__main__':
    pygame.init()
    screen_size = (300, 200)
    size        = 10
    clr         = [255, 0, 255]
    bg          = (255, 255, 0)
    font_size   = 15
    font        = pygame.font.Font(None, font_size)
    clock       = pygame.time.Clock()

    screen    = pygame.display.set_mode(screen_size)
    screen.fill(bg)

    button1 = button(position=(80, 100), size=(100, 50), clr=(220, 220, 220), cngclr=(255, 0, 0), func=fn1, text='button1')
    button2 = button((220, 100), (100, 50), (220, 220, 220), (255, 0, 0), fn2, 'button2')

    button_list = [button1, button2]

    crash = True
    while crash:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crash = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    crash = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    pos = pygame.mouse.get_pos()
                    for b in button_list:
                        if b.rect.collidepoint(pos):
                            b.call_back()

        for b in button_list:
            b.draw(screen)

        pygame.display.update()
        clock.tick(60)
Related