为什么我的print()命令在控制台中显示双打?

时间:2018-08-29 19:31:15

标签: python pygame

下面是我正在处理的一些代码,它们将双打打印到CMD窗口。 我看到这不是一个很大的问题,我只是担心,随着程序的发展,迟早它可能会变成一个更大的问题。

这是当我左键单击时CMD向我显示的示例:

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

为了简洁起见,我遗漏了很多代码,并将其精确定位到这些类和函数上。我事先表示歉意-我对这个网站和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 个答案:

答案 0 :(得分:1)

之所以会这样,是因为您在for循环中为button.handle_event(event)组中的每个按钮调用了self.all_sprites,所以您正在为每个按钮打印print( Button.whichButton(event)+' mouse pressed at ' + str(event.pos))

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)