繁体   English   中英

pygame的“按钮”功能未检测到鼠标事件

[英]pygame 'button' function not detecting mouse events

我从一个较旧的项目中复制了此功能,该功能在其上可正常运行,但不再起作用。 该按钮应该能够检测到光标何时位于其上方,并以较浅的颜色重新绘制其自身,然后,当光标移开时,它将以通常的较深颜色重新绘制其自身。 但是现在,当光标在其上方时,它不会改变。 它也不响应单击。 这是代码

def button(text, x, y, width, height, inactive_color, active_color, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + width > cur[0] > x and y + height > cur[1] > y:
        pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
        pygame.display.update()
        if click[0] == 1 and action != None:
            if action == 'correct':
                print('correct!')
    else:
        pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))

    text_to_button(text, black, x, y, width, height)
    pygame.display.update()

button('test', 100, 100, 100, 50, darkGreen, green, action = 'correct')

您一次调用button功能。 它贯穿该函数的代码并终止,并且不对任何输入做出进一步的响应-因为它仅运行了一次(几乎立即)。

也许如果您每次在Pygame evnet队列中发生鼠标移动事件时都调用此方法,则它可能会起作用。

或者,考虑为此使用对象而不是函数,例如:

class Button():
    def __init__(self, x, y, width, height, text, action):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text
        self.action = action
        self.label = myfont.render(self.text, 1, (0,0,0))


    def render(self, window):
        if self.visible == True:
            pygame.draw.rect(window, (255,255,255), [self.x, self.y, self.width, self.height])
            window.blit(self.label, (self.x, self.y))

    def pressed(self):
            self.action(self.arguments)

    def hover(self):
            #Here you can implement your code that handles when the mouse hovers over the button. This method can be called by checking mouse movement events in your main loop and seeing if they lie within the coordinates, width, and height of the button. 

暂无
暂无

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

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