[英]Python kivy app with kv and py files for every screen
Please explain how I can create an application on kivy so that each screen has separate py and kv files.请解释我如何在 kivy 上创建应用程序,以便每个屏幕都有单独的 py 和 kv 文件。 Including screens that are called from screens.
包括从屏幕调用的屏幕。 In fact, we need an example application of the form: Mainscreen-> 1screen-> 2screen
其实我们需要一个窗体的示例应用:Mainscreen-> 1screen-> 2screen
Here is one way to do it:这是一种方法:
main.py:主要.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
class WindowManager(ScreenManager):
pass
class TestApp(App):
def build(self):
return Builder.load_file('main.kv') # this method can be eliminated if `main.kv` is renamed to `test.kv`
if __name__ == '__main__':
TestApp().run()
main.kv:主.kv:
# import the python files defining the Screens
#: import Screen1 screen1.Screen1
#: import Screen2 screen2.Screen2
# include the kv files for the other Screens
#: include screen1.kv
#: include screen2.kv
WindowManager:
Screen1:
Screen2:
screen1.py:屏幕1.py:
from kivy.uix.screenmanager import Screen
class Screen1(Screen):
pass
screen1.kv: screen1.kv:
<Screen1>:
name: 'screen1'
BoxLayout:
Label:
text: 'Screen1'
Button:
text: 'back'
on_release: app.root.current = 'screen2'
screen2.py:屏幕2.py:
from kivy.uix.screenmanager import Screen
class Screen2(Screen):
pass
screen2.kv: screen2.kv:
<Screen2>:
name: 'screen2'
BoxLayout:
Label:
text: 'Screen2'
Button:
text: 'back'
on_release: app.root.current = 'screen1'
Of course, there are different ways to do this.当然,有不同的方法可以做到这一点。 Another approach is to import all the
py
files in main.py
and just use Builder.load_file()
in main.py
for each kv
file另一种方法是导入
main.py
中的所有py
文件,并在main.py
中为每个kv
文件使用Builder.load_file()
If you put all the files (except main.py) in a subfolder named subs
, then you just need to make a change to main.py:如果您将所有文件(除了 main.py)放在名为
subs
的子文件夹中,那么您只需对 main.py 进行更改:
class TestApp(App):
def build(self):
return Builder.load_file('subs/main.kv')
And changes to main.kv
:并更改
main.kv
:
# import the python files defining the Screens
#: import Screen1 subs.screen1.Screen1
#: import Screen2 subs.screen2.Screen2
# include the kv files for the other Screens
#: include subs/screen1.kv
#: include subs/screen2.kv
WindowManager:
Screen1:
Screen2:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.