我曾经通过在单个 .kv 文件中定义所有内容(包括屏幕)来设法使多屏幕程序运行。
通过使用 root.current
(在 .kv 文件中)或 self.root.current
(在 Python 文件中),我能够在屏幕之间切换。然而,一旦有多个屏幕包含许多小部件,.kv 文件就会变得非常大并且难以维护。
这次我尝试在单独的 .kv 文件中定义屏幕,但无法在屏幕之间进行切换。到目前为止,每次尝试都会导致错误(语法无效、屏幕名称未定义...)。
有没有办法在单独的 .kv 文件中定义的屏幕之间切换? 以下是我正在使用的文件:
main.py
from kivy.app import App
class MainApp(App):
pass
if __name__ == '__main__':
MainApp().run()
main.kv:
#:include screen_1.kv
#:include screen_2.kv
#:import NoTransition kivy.uix.screenmanager.NoTransition
ScreenManager:
transition: NoTransition()
Screen:
name: "main_screen"
BoxLayout:
orientation: "vertical"
Label:
text: "main screen"
Button:
text: "to screen 1"
on_press: app.root.current = "screen_1"
Button:
text: "to screen 2"
on_press: app.root.current = "screen_2"
screen_1.kv:
Screen:
name: 'screen_1'
BoxLayout:
orientation: "vertical"
Label:
text: "Screen 1"
Button:
text: "to main screen"
on_press: app.root.current = "main_screen"
Button:
text: "to screen 2"
on_press: app.root.current = "screen_2"
screen_2.kv:
Screen:
name: 'screen_2'
BoxLayout:
orientation: "vertical"
Label:
text: "Screen 2"
Button:
text: "to main screen"
on_press: app.root.current = "main_screen"
Button:
text: "to screen 1"
on_press: app.root.current = "screen_1"
最佳答案
解决方案
- 添加dynamic class进入
screen_1.kv
和screen_2.kv
,例如<Screen1@Screen>:
和<Screen2@Screen>:
分别。 - 实例化屏幕,
Screen1:
和Screen2:
在main.kv
示例
screen_1.kv
<Screen1@Screen>:
name: 'screen_1'
BoxLayout:
orientation: "vertical"
Label:
text: "Screen 1"
Button:
text: "to main screen"
on_press: app.root.current = "main_screen"
Button:
text: "to screen 2"
on_press: app.root.current = "screen_2"
screen_2.kv
<Screen2@Screen>:
name: 'screen_2'
BoxLayout:
orientation: "vertical"
Label:
text: "Screen 2"
Button:
text: "to main screen"
on_press: app.root.current = "main_screen"
Button:
text: "to screen 1"
on_press: app.root.current = "screen_1"
main.kv
#:include screen_1.kv
#:include screen_2.kv
#:import NoTransition kivy.uix.screenmanager.NoTransition
ScreenManager:
transition: NoTransition()
Screen:
name: "main_screen"
BoxLayout:
orientation: "vertical"
Label:
text: "main screen"
Button:
text: "to screen 1"
on_press: app.root.current = "screen_1"
Button:
text: "to screen 2"
on_press: app.root.current = "screen_2"
Screen1:
Screen2:
输出
关于python - 在单独的 .kv (Kivy) 文件中定义的屏幕之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51469076/