Kivy——图像作为按钮 [英] Kivy-- Image as Button

查看:35
本文介绍了Kivy——图像作为按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是 kivy 和面向对象编程的初学者.

I am just beginner in kivy and object oriented programming.

我一直在结合这里的教程练习这段代码:

I have been practicing this code as a combination of the tutorials here:

from kivy.uix.behaviors import ButtonBehavior  
from kivy.uix.image import Image  
from kivy.lang import Builder  
from kivy.app import App  
from kivy.uix.floatlayout import FloatLayout  

Builder.load_string("""  
<ImageButton>:  
    FloatLayout:  
        Image:  
            source:'resizedA.png'  
            size_hint: .2, .2  
""")  

class ImageButton(ButtonBehavior,FloatLayout, Image):  
    def on_press(self):  
        print ('pressed')


class The_AssignmentApp(App):  
    def build(self):  
        return ImageButton()  

if __name__ == "__main__":  
    The_AssignmentApp().run()  

我的问题是,为什么即使我按下屏幕的其他部分(不是图像),应用程序仍然认为整个屏幕是一个按钮?

My question is, why is that even if I press the other parts of the screen(not the image), the app still considers the whole scree as a button?

请原谅我的无知,我真的很想学习.谢谢!

Pardon my ignorance here, I would really want to learn. Thanks!

推荐答案

class ImageButton(ButtonBehavior,FloatLayout, Image):  

不要从多个小部件(在本例中为 FloatLayout 和 Image)继承,这会导致一些奇怪的错误.

Don't inherit from multiple widgets (in this case FloatLayout and Image), this will lead to some weird bugs.

至于您的具体问题,ButtonBehavior 是 ImageButton 的父类,它是根小部件并填充屏幕.出于这个原因,整个屏幕一个按钮,尽管您显然不打算这样做.

As for your specific problem, the ButtonBehavior is a parent class of the ImageButton which is the root widget and fills the screen. For this reason, the whole screen is a button, though you clearly intended otherwise.

以下是否更符合您的要求?您也可以只使用 FloatLayout 而不是创建新的 RootWidget 类,我这样做是为了适应您已经编写的内容.

Is the following more like what you wanted? You can also just use a FloatLayout instead of creating the new RootWidget class, I just did this to fit with what you already wrote.

from kivy.uix.behaviors import ButtonBehavior  
from kivy.uix.image import Image  
from kivy.lang import Builder  
from kivy.app import App  
from kivy.uix.floatlayout import FloatLayout  

class RootWidget(FloatLayout):
    pass

class ImageButton(ButtonBehavior, Image):  
    def on_press(self):  
        print ('pressed')

Builder.load_string("""  
<RootWidget>:  
    ImageButton:  
        source:'resizedA.png'  
        size_hint: .2, .2  
""")  

class The_AssignmentApp(App):  
    def build(self):  
        return RootWidget()

if __name__ == "__main__":  
    The_AssignmentApp().run()  

这篇关于Kivy——图像作为按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆