[英]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. 我对Kivy有点陌生,我一直在寻找一种方法来使光标悬停在按钮上,以使其动起来。
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. 在这个问题已经(大部分)回答了这个帖子 。还有就是一个非常好的例子在这里下LGPL许可证由Olivier POYEN。 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). 基本上,他定义了一个名为
HoverBehavior
的类,您应该继承该类以创建一个新类,例如HoverButton
或HoverLabel
(如他的示例所示)。 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. 然后,您可以访问
on_enter
和on_leave
函数,可用于更改按钮的图像,更改标签的文本颜色或任何所需的功能。
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: 为了回答您的确切问题,我将寻求理解
HoverBehavior
类,然后从上面的源复制/粘贴它,然后像这样创建一个新类:
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: 或者您可以使用看起来更简洁的kv语言:
<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: 如果使用第二个选项,只需确保在您的python脚本中包括
HoverButton
的基类:
class HoverButton(Button, HoverBehavior):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.