Search code examples
pythoneventsspritemousepyglet

Mouse hover on Sprite object Pyglet?


I want to know if there is a way to catching mouse hover on sprite object with Pyglet?

my_sprite = pyglet.sprite.Sprite(image, x, y)

something like this in Tkinter :

sprite.bind(circle, "<Enter>", on_enter)

Solution

  • Below is a demo code for detecting mouse hover on a moving gif sprite, u can have a try and change it to what u like.

    import pyglet
    from pyglet.window import mouse
    
    
    animation = pyglet.image.load_animation('ur_image_gif_path_like_xxx.gif')
    bin = pyglet.image.atlas.TextureBin()
    animation.add_to_texture_bin(bin)
    sprite = pyglet.sprite.Sprite(img=animation)
    window = pyglet.window.Window()
    
    @window.event
    def on_draw():
        window.clear()
        sprite.draw()
    
    def update(dt):
        sprite.x += dt*10
    
    @window.event
    def on_mouse_motion(x, y, dx, dy):
        # print(x, y, dx, dy)
        image_width = sprite.image.get_max_width()
        image_height = sprite.image.get_max_height()
        if sprite.x+image_width>x>sprite.x and sprite.y+image_height>y>sprite.y:
            print("mouse hover sprite")
        else:
            print("mouse leave sprite")
    
    pyglet.clock.schedule_interval(update, 1/60.)
    pyglet.app.run()