0

I tried to put a button in my code, but it will either show my button or the program(not both of them in the same program together). I commented out the sentence of code that is causing this problem[this is in the def redraw()]. The following code is what I have tried out so far:

class GameLevel:

    def __init__(self, screen):
        pygame.init()
        self.screen = screen
        background_image = pygame.image.load("grass.jpg")
        self.background = pygame.transform.scale(background_image, screen.get_size())
        self.platforms = pygame.sprite.Group()
        self.player_objects = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()

        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, screen, outline=None):
                # Call this method to draw the button on the screen
                if outline:
                    pygame.draw.rect(screen, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

                pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), 0)

                if self.text != '':
                    font = pygame.font.SysFont('comicsans', 45)
                    text = font.render(self.text, 1, (0, 0, 0))
                    screen.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

        def redrawWindow():
            #screen.fill((0,0,0))
            greenButton.draw(screen, (0, 0, 0))

        run = True
        greenButton = button((235, 198, 52), 5, 5, 100, 50, 'Pause')
        while run:
            redrawWindow()
            pygame.display.update()

            for event in pygame.event.get():
                pos = pygame.mouse.get_pos()

                if event.type == pygame.QUIT:
                    run = False
                    pygame.quit()
                    quit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if greenButton.isOver(pos):
                        print('PAUSED')

                if event.type == pygame.MOUSEMOTION:
                    if greenButton.isOver(pos):
                        greenButton.color = (235, 198, 52)
                    else:
                        greenButton.color = (235, 155, 52)

0 Answers0