Why are my print() commands showing doubles in the console?

Viewed 94

Below is some code I'm working on that is printing doubles to the CMD window. It's not a huge issue that I'm seeing doubles, I'm just worried that sooner or later it may turn into a larger problem when this program grows.

This is an example of what CMD shows me when I left click:

Left mouse pressed at (451, 279)
Left mouse pressed at (451, 279)
Left mouse released at (451, 279)
Left mouse released at (451, 279)

I've left out a lot of code for brevity, and pinpointed it to these classes and functions. I apologize in advance - I'm very new to this site, and python.

class Button:       
    def whichButton(self):
        #this function takes the mousebuttondown event, and returns WHICh button is pressed
        if self.button == 1:
            return "Left"
        if self.button == 2:
            return "Middle"
        if self.button == 3:
            return "Right"
        if self.button == 4:
            return "Wheel Up"
        if self.button == 5:
            return "Wheel Down"     

    def handleEvent(self, event):

        if event.type == pygame.MOUSEBUTTONDOWN:
            print( Button.whichButton(event)+' mouse pressed at ' + str(event.pos))
            if self.rect.collidepoint(event.pos):
                self.buttonDown = True
                self.image = self.imageDown

class Game:
    self.all_sprites.add(self.startButton, self.quitButton)
    def run(self):
        while not self.done:
            self.frameRate = self.clock.tick(60) / 1000
            self.handleEvent()


    def handleEvent(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            for button in self.all_sprites:
                button.handleEvent(event)




if __name__ == '__main__':
    pygame.init()
    Game(screen).run()
    pygame.quit()
1 Answers

That happens because you're calling button.handle_event(event) for each button in the self.all_sprites group in a for loop, so you're printing print( Button.whichButton(event)+' mouse pressed at ' + str(event.pos)) for each button.

def handle_events(self):
    for event in pg.event.get():
        if event.type == pg.QUIT:
            self.done = True
        # Iterates over all buttons in the group and calls their `handle_event` method.
        for button in self.all_sprites:
            button.handle_event(event)
Related