2014-11-08 51 views
1

我是Kivy的新手。我想要一个图像在按下(触摸)时变成另一个图像。 应该有一些简单的方法做到这一点,但我不能找出什么。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] 

这是我的代码的一部分。我不知道如何让我的形象“可压缩”。它是否必须是某种按钮?

+0

RTM:[例如,如果你想要一个“按钮”功能添加到图片,你可以做...](http://kivy.org/docs/api-kivy.uix.behaviors.html) – 2014-11-10 16:08:37

回答

1

我相信你可以做到这一点的最好办法,是用在KV文件即时创建一个动态类 http://kivy.org/docs/api-kivy.lang.html#dynamic-classes

<[email protected]+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

2

不,它并不一定是一个按钮。在不添加任何额外对象的情况下,您还可以使用widget类的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) 

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

之前你虽然开始沿着这条道路,是否考虑到你的目标将通过预定义类如满足按照您的建议修改按钮的背景属性。这可能是从长远来看,要简单得多,如果你也想要的是,kivy开发者已经建立的其他复杂行为的

+0

没有这个回答这个问题? – tiktok 2014-11-16 12:20:26