screenmanager kivy定义了用于切换屏幕的回调函数

时间:2018-10-08 16:17:48

标签: android python kivy

我想用kivy切换python文件中的屏幕。 我希望通过回调函数gonext 实现。如何定义这个? 当我运行代码时,它显示mainwidgetApp,但该按钮不起作用。 这是我尝试过的: 将sm更改为global(可能不是一个好主意)。 将mainwidget的kivy文件更改为: on_press:root.manager.current ='设置'

这是我的代码:

Builder.load_string("""
<MenuScreen>:
 mainwidgetApp






<SettingsScreen>:
 BoxLayout:
    Button:
        text: 'My settings button'
    Button:
        text: 'Back to menu'
        on_press: root.manager.current = 'settings'
""")


 class mainwidget(Widget):




def __init__(self, **kwargs):

    btnnext = Button(text='go to next', pos=(200, 400))
    btnnext.bind(on_press=self.gonext)
    self.add_widget(btnnext)


# def savecard(self, btn_instance):




def gonext(self ,btn_inst):

  ScreenManager().current = "SettingsScreen"

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))



class mainwidgetApp(App):

 def build(self):   
    Window.clearcolor = (0,0,0.3,1)
    return mainwidget()



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


class TestApp(App):

 def build(self):
    return sm

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

1 个答案:

答案 0 :(得分:0)

  1. ScreenManager().current = "SettingsScreen"替换为sm.current = "settings"
  2. 将类名从mainwidget重命名为MainWidget(约定CapWords

示例

main.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.lang import Builder


Builder.load_string("""
#:kivy 1.11.0

<MenuScreen>:
    MainWidget:


<SettingsScreen>:
    BoxLayout:
        Button:
            text: 'My settings button'
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'settings'
""")


class MainWidget(Widget):

    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)
        print("\nmainwidget:")
        btnnext = Button(text='go to next', pos=(200, 400))
        btnnext.bind(on_press=self.gonext)
        self.add_widget(btnnext)

    # def savecard(self, btn_instance):

    def gonext(self ,btn_inst):
        sm.current = "settings"


class MenuScreen(Screen):
    pass


class SettingsScreen(Screen):
    pass


class ScreenManager(ScreenManager):
    pass

# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SettingsScreen(name='settings'))


class TestApp(App):

    def build(self):
        Window.clearcolor = (0,0,0.3,1)
        return sm


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

输出

Img01 - App Starup Img02 - Pressed Button, 'go to next'