简体   繁体   中英

How to animate a button on kivy when the cursor is over it?

I'm kinda new to Kivy and I was looking for a way to animate the button when the cursor is over it.

I've tried to manage a way to get the mouse position and compare it with the button coordinates but no success at all.

This question has already been (mostly) answered at this post .There is a very nice example of this here by Olivier POYEN under LGPL license. Basically he has defined a class called HoverBehavior that you should inherit from to make a new class, eg HoverButton or HoverLabel (as his example shows). Then you have access to the on_enter and on_leave functions, which you can use to change the button's image, or change a label's text color, or whatever you need.

To answer your exact question, I would seek to understand the HoverBehavior class, then copy/paste it from the source above, then make a new class like so:

class HoverButton(Button, HoverBehavior):
    def on_enter(self, *args):
        self.background_normal = "some_image1.png" # Change the button's image when entered
    def on_leave(self, *args):
        self.background_normal = "some_other_image.png" # Change image when leaving

or you could use the kv language which looks even cleaner:

<HoverButton>:
    background_normal: "some_image1.png" if self.hovered else "some_other_image.png"

just make sure you include a base class for the HoverButton in your python script if you use the 2nd option:

class HoverButton(Button, HoverBehavior):
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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