【问题标题】:kivy: how to make an image act like a buttonkivy:如何使图像像按钮一样
【发布时间】:2015-01-05 10:47:08
【问题描述】:

我是 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]

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

【问题讨论】:

标签: python image button widget kivy


【解决方案1】:

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

<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) 

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 开发人员已经内置的一些其他复杂行为,从长远来看,这可能会简单得多。

【讨论】:

  • 这回答了问题吗?
【解决方案2】:

我相信你能做到这一点的最好方法是在你的 kv 文件中使用动态创建的类 http://kivy.org/docs/api-kivy.lang.html#dynamic-classes

<ImageButton@ButtonBehavior+Image>:
     on_press: self.parent.callback()
# this class is created on the fly, named ImageButton and subclasses ButtonBehavior and Image
# It's basically an Image that can act like a Button.

<Game>
   ImageButton:
     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]

其中callback()Game 中用于更改图像来源的方法。

Game类里面:

def callback(self, instance, value):
    self.ids['11'].source = new_source
# or you could switch sources each click for instance

或类似的东西(看这里:http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 2013-04-14
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多