9

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!

inclement
  • 29,124
  • 4
  • 48
  • 60
Melquiades
  • 93
  • 1
  • 1
  • 4

1 Answers1

12
class ImageButton(ButtonBehavior,FloatLayout, Image):  

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

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.

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()  
inclement
  • 29,124
  • 4
  • 48
  • 60
  • 2
    I didn't understand how this could be used to fire an arbitrary function but this page of the documentation (https://kivy.org/doc/stable/api-kivy.uix.behaviors.html) did make it clear. You simply have to add a class `ImageButton(ButtonBehavior, Image): pass`. Then you can use `ImageButton(source="PATH/TO/IMAGE", on_press=some_function())` to let the image act as a Button. – New2Coding Sep 10 '18 at 08:41