Detect mouseover an image in Pygame

僤鯓⒐⒋嵵緔 提交于 2019-11-29 11:07:20
sloth

Use Surface.get_rect to get a Rect describing the bounds of your Surface, then use .collidepoint() to check if the mouse cursor is inside this Rect.


Example:

if newGameButton.get_rect().collidepoint(pygame.mouse.get_pos()):
    print "mouse is over 'newGameButton'"
hammythepig

I'm sure there are more pythonic ways to do this, but here is a simple example:

button_x = 0
button_y = 0
newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha()
x_len = newGameButton.get_width()
y_len = newGameButton.get_height()
mos_x, mos_y = pygame.mouse.get_pos()
if mos_x>button_x and (mos_x<button_x+x_len):
    x_inside = True
else: x_inside = False
if mos_y>button_y and (mos_y<button_y+y_len):
    y_inside = True
else: y_inside = False
if x_inside and y_inside:
    #Mouse is hovering over button
screen.blit(newGameButton, (button_x,button_y))

Read more on the mouse in pygame, as well as surfaces in pygame.

Also here is an example closely related to this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!