我试图从Screenmanager类的Screenmanager调用Screen类中的def,但是我不能。
我想创建一个框布局,并在调用ScreenManager后立即启动该应用程序时在该框布局中放置一个按钮,因此它是默认屏幕。 我想这样做,所以我可以在按下按钮时使用self.parent.current ='屏幕名称'在多个屏幕之间切换
这是代码
class Manager(ScreenManager):
def __init__(self):
self.add_widget(Scr1().make_button())
class Scr1(Screen):
def __init__(self):
self.layout = BoxLayout(orientation = 'vertical')
self.button = Button(text='hello')
self.layout.add_widget(self.button)
def make_button(self, layout):
return self.layout
class MainApp(App):
def build(self):
sm =Manager()
s1 = Scr1()
sm.add_widget=s1
return sm
if __name__ == "__main__":
MainApp().run()
这是我得到的错误
Traceback (most recent call last):
File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 43, in <module>
MainApp().run()
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\app.py", line 829, in run
root = self.build()
File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 37, in build
sm =Manager()
File "C:/Users/user/Desktop/CarsonMusic/Learn.py", line 24, in __init__
self.add_widget(Scr1().make_button())
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\uix\screenmanager.py", line 979, in add_widget
'ScreenManager accepts only Screen widget.')
kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget.
我知道我可能犯了一个愚蠢的错误,但是有人可以帮助我吗?
答案 0 :(得分:0)
我解决了!我必须删除Manager(ScreenManager)类,添加“ super”,然后将布局小部件添加到self
这是我的新代码:
class Scr1(Screen):
def __init__(self, **kwargs):
super (Scr1, self).__init__(**kwargs)
self.layout = BoxLayout(orientation='vertical')
self.button = Button(text='hello')
self.button.bind(on_press=self.screen2)
self.layout.add_widget(self.button)
self.add_widget(self.layout)
def screen2(self, *args):
self.manager.current = 'screen2'
class Scr2(Screen):
def __init__(self, **kwargs):
super (Scr2,self).__init__(**kwargs)
self.layout2 = BoxLayout(orientation='vertical')
self.add_widget(self.layout2)
self.button2 = Button(text='hello2')
self.button2.bind(on_press=self.screen1)
self.layout2.add_widget(self.button2)
def screen1(self, *args):
self.manager.current = 'screen1'
class MainApp(App):
def build(self):
sm= ScreenManager()
screen1 = Scr1(name='screen1')
screen2= Scr2(name='screen2')
sm.add_widget(screen1)
sm.add_widget(screen2)
return sm
if __name__ == "__main__":
MainApp().run()