简体   繁体   English

我如何在 kivy python 中的不同布局类之间进行通信

[英]How can i communicate between diffrent layout classes in kivy python

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.我正在尝试使 MainLayout 上的按钮称为 add,将另一个按钮添加到作为其子项之一的 stacklayout 中。 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.在这样做时,我必须在它们之间共享一个变量和一个功能,以在堆栈布局上实现 add_widget 函数。 no matter what I do, I can't find a solution无论我做什么,我都找不到解决方案

code main.py:代码 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:和 kv 文件:

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:

To allow easy navigation in your GUI, you can use ids .为了在您的 GUI 中轻松导航,您可以使用ids Here is a modified version of your kv with two new ids :这是带有两个新idskv的修改版本:

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:然后,您的add_button()方法可以是:

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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