Search code examples
python-3.xkivy

how to link main.py class and my.kv rule?


i wonder whether there is a convenient method to create widget class in main.py and link it to my.kv ,it is sccessful in MyLayout but fail in MyModalView

First,following is my code

main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.modalview import ModalView


class MyModalView(ModalView):
    pass

class MyLayout(GridLayout):
    a1 = MyModalView()

    def btn1(self):
        self.a1.open()
        #self.a1.dismiss()


class Myapp(App):

    def build(self):
        return MyLayout()


if __name__ == '__main__':
    Myapp().run()

my.kv

<MyModalView>:

    Button:
        text:'starting point'


<MyLayout>:
    rows:2

    Button:
        text: 'press me'
        on_press: root.btn1()

    Label:
        text: 'hello world

when I press the button,the pycharm show this result: enter image description here

but the result which I want is like this enter image description here

I change main.py code to show this result which I want,but I really want to know is it possible to change my.kv only to show the same result?

main.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.modalview import ModalView
from kivy.uix.button import Button



class MyModalView(ModalView):
    def __init__(self):
        super(MyModalView,self).__init__()
        self.add_widget(Button(text='apple'))
    pass


class MyLayout(GridLayout):
    a1 = MyModalView()

    def btn1(self):
        self.a1.open()


class Myapp(App):

    def build(self):
        return MyLayout()


if __name__ == '__main__':
    Myapp().run()

my.kv

<MyLayout>:
    rows:2

    Button:
        text: 'press me'
        on_press: root.btn1()

    Label:
        text: 'hello world'

Solution

  • You can open the MyModalView from within the kv by using Factory:

    #:import Factory kivy.factory.Factory
    
    <MyModalView>:
    
        Button:
            text:'starting point'
    
    
    <MyLayout>:
        rows:2
    
        Button:
            text: 'press me'
            on_press: Factory.MyModalView().open()
    
        Label:
            text: 'hello world'