简体   繁体   English

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

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

As part of a game, I am attempting to create a login page in pygame.作为游戏的一部分,我试图在 pygame 中创建一个登录页面。 As I require buttons I have been trying to get a button function (that I saw on another tutorial page) to work.因为我需要按钮,所以我一直在尝试使按钮功能(我在另一个教程页面上看到的)起作用。 However, I seem to run into a problem with getting the program to register when the mouse is clicked.但是,我似乎遇到了在单击鼠标时让程序注册的问题。 Below I have pasted my function for the button:下面我粘贴了我的按钮功能:

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()

Each time I run my program - no matter what I do, my buttons remain static objects and do not change colour or allow any actions to run.每次我运行我的程序时——无论我做什么,我的按钮都是静态对象,不会改变颜色或允许任何操作运行。 Additionally the line 'print(click)' only ever outputs (0,0,0).此外,'print(click)' 行只输出 (0,0,0)。 I am using a laptop to code this program so maybe my trackpad is what is causing issues?我正在使用笔记本电脑编写这个程序,所以也许我的触控板是导致问题的原因? I'm not too sure really but any alternatives on how to get this function to work would be much appreciated!我真的不太确定,但任何有关如何使此功能正常工作的替代方案都将不胜感激!

With Pygame you usually run an event function in your main loop that handles all your events.使用 Pygame,您通常会在主循环中运行一个事件函数来处理所有事件。

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

In your event function you can write something like this:在您的事件函数中,您可以编写如下内容:

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')

Hope this helps!希望这可以帮助!

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

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