简体   繁体   中英

How to use button behavior with screenmanager without .kv file in kivy

I need help on how to use kivy 'button behavior' with screen manager without any.kv file. I have tried but am getting errors.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Buttonbehavior 
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition


class ScreenManagement(ScreenManager):
    def __init__(self, **kwargs):
        super(ScreenManagement, self).__init__(**kwargs)

class Screen2(Screen):
    def __init__(self, **kwargs):
        super(Screen2, self).__init__(**kwargs)
        Pass

class Screen1(Screen, ButtonBehavior,Image):
    def __init__(self, **kwargs):
        super(Screen1,self).__init__(**kwargs)
        self.welc = Label(text='hi there welcome to my first screen', font_size=15, size_hint=(.26, .26),
                          pos_hint={'center_x': .5, 'center_y': .7})
        self.add_widget(self.welc)

#This is where I want the image to have buttonbehaviour and be clickable
        self.goto= ImageButton(source='put_any.png', size_hint=(.3, .2),
                       pos_hint={'center_x': .5, 'center_y': .32}, on_press=(source='put_any.png'), on_release=(source='put_any.png'))
        self.add_widget(self.goto)


class Application(App):
    def build(self):
        sm = ScreenManagement(transition=FadeTransition())
        sm.add_widget(Screen1(name='screen1'))
        sm.add_widget(Screen2(name='screen2'))
        return sm


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

I know I can do this with button widget but I want to use image and make it use button behavior. Making the image clickable.

Make a class ImageButton

from kivy.uix.behaviors import ButtonBehavior  
from kivy.uix.image import Image  

class ImageButton(ButtonBehavior, Image):
    pass

Now you can use ImageButton(source="some/path", on_press=some_function()) in any Layout or App

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM