我想制作一个按钮小部件。这是我的代码:
class Button(pg.sprite.Sprite):
def __init__(self, *, command, image, pos):
pg.sprite.Sprite.__init__(self)
self.command = command
self.image = pg.image.load(image).convert()
self.rect = self.image.get_rect(topleft= pos)
self.ButtonDown = False
def update(self, *args):
mouse = pg.mouse.get_pos()
clicked = pg.mouse.get_pressed()
if self.rect.collidepoint(mouse):
if clicked[0] and self.ButtonDown == False:
self.ButtonDown = True
self.command()
elif not clicked[0]:
self.ButtonDown = False
如何改善self.ButtonDown的功能?
我建议使用pygame均匀处理(请参阅pygame.event
)。评估pygame.event
中的事件列表,并在按下鼠标按钮时执行update
。 command
仅在按下按钮时出现一次: