Python / Kivy-将变量从一个类发送到另一个类

时间:2019-11-05 23:40:57

标签: python-3.x kivy kivy-language

我对Python并不陌生,所以我有一个基本的了解,但我也不会说我也很出色。

我尝试在Kivy中制作的巴西柔术应用存在很多问题。我试图从已在一个窗口中按下的按钮获取文本,然后在显示的下一个窗口的标签中使用该文本。我为前一个窗口指定了类名GuardWindow(),而后一个窗口称为SweepSubTranPage()

我已经设法轻松地将按钮的名称从kivy文件发送到类GuardsWindow(),并且行self.guardlabel = instance.text可以正常工作,并且可以完美地检索按钮名称。但是,我的主要问题是将该名称发送到SweepSubTranPage(),以便我可以在我的kivy文件中访问它。

这是Python代码:

class GuardsWindow(Screen):

    guardButtonName = ObjectProperty(None)

    def send_guard_type(self, instance, **kwargs):
        self.guardButtonName = instance.text      # retrieves the button name


    def sender(self):            # my attempt at sending it to the other class
        return self.guardButtonName


class SweepSubTranPage(Screen):

    pageTitle = ObjectProperty(None)
    gw = GuardsWindow()
    pageTitle.text = gw.sender()


kv = Builder.load_file("my.kv")


class MyMainApp(App):
    def build(self):
        return kv

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

这是Kivy文件代码:

<GuardsWindow>
    name: "GuardsHomepage"

    ScrollView:
        bar_width: 10
        do_scroll_x: False
        do_scroll_y: True
        scroll_type: ["bars", "content"]

        BoxLayout:
            orientation: "vertical"
            size_hint: 1, 2
            padding: 10
            spacing: 10

            Button:                  # these are the buttons that i am getting the text from
                text: "Full Guard"
                on_press:
                    root.send_guard_type(self)    # this sends the button
                on_release:
                    app.root.current = "SweepSubTranPage"
                    root.manager.transition.direction  = "left"


            Button:
                text: "Half Guard"
                on_press:
                    root.send_guard_type(self)    # this sends the button
                on_release:
                    app.root.current = "SweepSubTranPage"
                    root.manager.transition.direction  = "left"


<SweepSubTranPage>
    name: "SweepSubTranPage"
    pageTitle: title   

    BoxLayout:
        orientation: "horizontal"
        size_hint: 1, 0.1

        Label:              # this is the label that I need the text for
            id: title
            font_size: 40
            size_hint: 1, 1

运行上面的代码时,出现错误:

   File "C:/Users/bensw/PycharmProjects/BJJ Tracker/main.py", line 36, in <module>
     class SweepSubTranPage(Screen):
   File "C:/Users/bensw/PycharmProjects/BJJ Tracker/main.py", line 40, in SweepSubTranPage
     pageTitle.text = gw.sender()
 AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'text'

我希望我已经足够清楚地解释了我的问题。如果您有任何问题,请询问! 非常感谢!!

1 个答案:

答案 0 :(得分:1)

在您的send_guard_type()方法中,您可以使用任何Screen的{​​{1}}属性和{{1}的manager方法访问另一个Screen }。像这样:

get_screen()