Home > Software design >  How can i communicate between diffrent layout classes in kivy python
How can i communicate between diffrent layout classes in kivy python

Time:06-28

I wanted to know how can i make communication between multiple classes of the layout. I'm trying to make the button on the MainLayout called add, add another button to the stacklayout which is one of its children. in doing so, I have to both share a variable and also a functionality between them to implement the add_widget function on the stack layout. no matter what I do, I can't find a solution

code main.py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.metrics import dp
from kivy.uix.stacklayout import StackLayout


class Buttons_layout(StackLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.number = 0

        for _ in range(5):
            self.number  = 1
            self.add_widget(Button(text=str(self.number),color=(200,100,100),size_hint=(0.2,None),height=dp(100)))

class MainWidget(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

    def add_button(self):
        #dont know what to do here..................
        pass

class CanvosExampleApp(App):
    pass

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

and the kv file:

MainWidget:

<Buttons_layout>:
<Scroll_layout@ScrollView>:
    Buttons_layout: 
        size_hint: 1,None
        height:self.minimum_height
<MainWidget>:
    Button:
        text:'add'
        on_press: root.add_button()
        size_hint:None,1
        width:dp(50)
    Scroll_layout:

CodePudding user response:

To allow easy navigation in your GUI, you can use ids. Here is a modified version of your kv with two new ids:

MainWidget:

<Buttons_layout>:
<Scroll_layout@ScrollView>:
    Buttons_layout: 
        id: butts  # new id
        size_hint: 1,None
        height:self.minimum_height
<MainWidget>:
    Button:
        text:'add'
        on_press: root.add_button()
        size_hint:None,1
        width:dp(50)
    Scroll_layout:
        id: scroll  # new id

Then, your add_button() method can be:

def add_button(self):
    scroll = self.ids.scroll  # get reference to the Scroll_layout
    butts = scroll.ids.butts  # get reference to the Buttons_layout
    butts.add_widget(Button(text='Added',color=(200,100,100),size_hint=(0.2,None),height=dp(100)))
  • Related