没有 .kv 文件的 Kivy ScreenManager

Kivy ScreenManager without .kv file

我正在尝试在没有 .kv 文件的情况下进行屏幕转换。如果没有 .kv,是否可以这样做?这是代码

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


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

class emotionRecog(Screen):
    def __init__(self, **kwargs):
        super(emotionRecog, self).__init__(**kwargs)
        self.button1 = Button(text="Next", size_hint=(1, .1))
        self.button1.bind(on_press=self.screenTransition())
        layout = BoxLayout(orientation="vertical")
        layout.add_widget(self.button1)
        return layout

    def screenTransition(self, *args):
        self.manager.current = 'test'


class CamApp(App):
    def build(self):
        sm = ScreenManagement(transition=FadeTransition())
        sm.add_widget(emotionRecog(name='emotion'))
        sm.add_widget(testW(name='test'))
        return sm


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

在 运行 之后我得到这些错误

     Traceback (most recent call last):
   File "C:\Study\KivyMultiScreen\main.py", line 53, in <module>
     CamApp().run()
   File "C:\Study\KivyMultiScreen\main.py", line 47, in build
     sm.add_widget(emotionRecog(name='emotion'))
   File "C:\Study\KivyMultiScreen\main.py", line 35, in __init__
     self.button1.bind(on_press=self.screenTransition())
   File "C:\Study\KivyMultiScreen\main.py", line 41, in screenTransition
     self.manager.current = 'test'
 AttributeError: 'NoneType' object has no attribute 'current'

Process finished with exit code 1

你能帮帮我吗?

您应该将回调本身绑定到 on_press 操作。这样,Kivy 可以稍后调用该函数。

改变

        self.button1.bind(on_press=self.screenTransition())

        self.button1.bind(on_press=self.screenTransition)

您的脚本引发该特定错误的原因是因为 Screen.manager 尚未在您在该行中调用 self.screenTransition 的位置设置。

您还可以查看 Kivy documentation 中的前几个示例。