0

I am trying to make a button class in pygame and python but i dont know how i put code for when i will click the button it will execute code

the code i want to execute is :-

num1 = 1
num2 = 100

num2 = int(rand)-1
rand =  (num1+num2)//2
text_screen(str(rand),"#DEA33E",font2,795,185)
pygame.display.update()

and this is the Button class

class Button2:
def __init__(self,text,width,height,pos,elevation):
    # Core Attributes
    self.pressed = False
    self.elevation = elevation
    self.dynamic_elevation = elevation
    self.original_y_pos = pos[1]

    # top rectangle
    self.top_rect = pygame.Rect(pos,(width,height))
    self.top_color = "#475F77"

    # bottom rectangle
    self.bottom_rect = pygame.Rect(pos,(width,elevation))
    self.bottom_color = "#354B5E"

    # text
    self.text_surf = font3.render(text, True, "#FFFFFF")
    self.text_rect = self.text_surf.get_rect(center = self.top_rect.center)

def draw(self):
    # elevation logic
    ot = 1
    ot = ot + 0
    self.top_rect.y = self.original_y_pos - self.dynamic_elevation
    self.text_rect.center = self.top_rect.center

    self.bottom_rect.midtop = self.top_rect.midtop
    self.bottom_rect.height = self.top_rect.height + self.dynamic_elevation

    pygame.draw.rect(screen,self.bottom_color,self.bottom_rect,border_radius = 12)
    pygame.draw.rect(screen,self.top_color,self.top_rect,border_radius=12)
    screen.blit(self.text_surf,self.text_rect)
    self.check_click()

def check_click(self):
    mouse_pos = pygame.mouse.get_pos()
    if self.top_rect.collidepoint(mouse_pos):
        self.top_color = "#D74B4B"
        if pygame.mouse.get_pressed()[0]:
            self.dynamic_elevation = 0
            self.pressed = True
        else:
            self.dynamic_elevation = self.elevation
            if self.pressed == True:
                self.pressed = False

also i want to do so like i can use the rand and num1,num2 variable outside the class

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

0

Read about Classes and Instance Objects. A class has no variables, it has attributes. YYou have to create one (or more) instances of the class, then you can access the attributes of the class:

button = Button2(...)
if button.pressed:
    # do somthing
    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174