【发布时间】:2020-07-10 07:40:13
【问题描述】:
我正在用 kivy 开发一个游戏,它有不同的关卡,每个关卡都有自己的 python kivy 文件。我正在使用屏幕管理器从一个屏幕级别移动到另一个屏幕级别。问题是如何使用 kivy 导入包含 main.py 文件中每个级别的那些 python Kivy 文件。我没有使用 .kv 文件。
# level1.py
import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label
class Level1(FloatLayout):
def __init__(self, **kwargs):
super(Level1, self).__init__(**kwargs)
self.btn1=Button(text='level 1', size_hint=(0.5, 0.5),
on_press=self.click_b1))
self.add_widget(self.btn1)
def click_b1(self, instance):
pass
class Level1App(App):
def build(self):
return Level1()
if __name__ == '__main__':
Level1App().run()
# level2.py
import kivy
from kivy.app import App
from kivy.uix.floatlayout import Floatlayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.label import Label
class Level2(FloatLayout):
def __init__(self, **kwargs):
super(Level2, self).__init__(**kwargs)
self.btn1=Button(text='level 2', size_hint=(0.5, 0.5),
on_press=self.click_b1))
self.add_widget(self.btn1)
def click_b1(self, instance):
pass
class Level2App(App):
def build(self):
return Level1()
if __name__ == '__main__':
Level2App().run()
如何在具有屏幕管理器的 main.py 中导入 level1.py 和 level2.py(不带 .kv)
# main.py with screen manager
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
class ScreenManagement(ScreenManager):
def __init__(self, **kwargs):
super(ScreenManagement, self).__init__(**kwargs)
class Level1Window(Screen):
def __init__(self, **kwargs):
super(Level1Window, self).__init__(**kwargs)
# run level1.py file here
class level2Window(Screen):
def __init__(self, **kwargs):
super(Level2Window, self).__init__(**kwargs)
# run level2.py file here
class Application(App):
def build(self):
sm = ScreenManagement(transition=FadeTransition())
sm.add_widget(Level1Window(name='#'))
sm.add_widget(Level2Window(name='#'))
return sm
if __name__ == "__main__":
Application().run()
【问题讨论】:
标签: python kivy kivy-language