繁体   English   中英

pygame.mouse.get_pressed() 在我的按钮功能中无法正常工作

[英]pygame.mouse.get_pressed() not working as I need in my button function

作为游戏的一部分,我试图在 pygame 中创建一个登录页面。 因为我需要按钮,所以我一直在尝试使按钮功能(我在另一个教程页面上看到的)起作用。 但是,我似乎遇到了在单击鼠标时让程序注册的问题。 下面我粘贴了我的按钮功能:

def button(self,msg,x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    print(click)
    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(screen, ac,(x,y,w,h))
        if click[0] == 1 and action != None:
            action()         
    else:
        pygame.draw.rect(screen, ic,(x,y,w,h))
    smallText = pygame.font.Font("freesansbold.ttf",20)
    textSurf, textRect = self.text_objects(msg, smallText)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    screen.blit(textSurf, textRect)
    pygame.display.update()

每次我运行我的程序时——无论我做什么,我的按钮都是静态对象,不会改变颜色或允许任何操作运行。 此外,'print(click)' 行只输出 (0,0,0)。 我正在使用笔记本电脑编写这个程序,所以也许我的触控板是导致问题的原因? 我真的不太确定,但任何有关如何使此功能正常工作的替代方案都将不胜感激!

使用 Pygame,您通常会在主循环中运行一个事件函数来处理所有事件。

while self.playing:
    self.draw()
    self.events()
    etc...

在您的事件函数中,您可以编写如下内容:

for event in pygame.event.get():

        # Always here to make it possible to exit when pressing X in game window:
        if event.type == pygame.QUIT:
                self.playing = False
                pygame.quit()
                quit()

        # Left mouse button down events:
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
                    if button.collidepoint(pos):
                        print('do what button is supposed to do')

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM