我从一个较旧的项目中复制了此功能,该功能在其上可正常使用,但不再起作用。该按钮应该能够检测到光标何时位于其上方,并以较浅的颜色重新绘制其自身,然后,当光标移开时,它将以通常的较深颜色重新绘制其自身。但是现在,当光标在其上方时,它不会改变。它也不响应单击。这是代码
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')
答案 0 :(得分:0)
您一次调用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.