kivy:如何使图像充当按钮

Mar*_*usz 4 python image widget button kivy

我是基维的新手。我希望图像在被按下(触摸)时变成不同的图像。应该有一些简单的方法可以做到这一点,但我不知道是什么。

<Game>
   Image:
     id: "11"
     center_x: root.width / 2 - root.height * 1/5 * 1.5 
     center_y: root.height * 1/5
     size: root.height / 6, root.height / 6
     source: root.images[0]
Run Code Online (Sandbox Code Playgroud)

这是我的代码的一部分。我不知道如何使我的图像“可按压”。它必须是某种按钮吗?

tik*_*tok 5

不,它不一定是一个按钮。在不添加任何额外对象的情况下,您还可以使用 widget 类(也恰好是 Image 的基类)的 on_touch_down 事件。

<Game>
    Image:
        id: "11"
        center_x: root.width / 2 - root.height * 1/5 * 1.5 
        center_y: root.height * 1/5
        size: root.height / 6, root.height / 6
        source: root.images[0]
        on_touch_down: root.image_press(*args) 
Run Code Online (Sandbox Code Playgroud)

args 包含事件的额外参数:http://kivy.org/docs/api-kivy.uix.widget.html?highlight=on_touch_down#kivy.uix.widget.Widget.on_touch_down。在这里,我假设您的处理程序名为 image_press 并添加到 Game 类中。

不过,在开始这条路之前,请考虑预定义的类是否可以实现您的目标,例如按照您的建议修改按钮的背景属性。从长远来看,如果您还想要 kivy 开发人员已经内置的一些其他复杂行为,那么从长远来看,这可能会简单得多。