Kivy class in .py and .kv interaction
我没有完全理解 python 文件中的类和 kivy 语言是如何交互的。我目前正在修改 Kivy 的 Showcase 示例以增加我的理解。
文件结构
- 主文件
- 陈列柜.kv
- 数据/屏幕/test.kv
主文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Testy(BoxLayout): ttext = 'Bla' #other code class ShowcaseScreen(Screen): fullscreen = BooleanProperty(False) def add_widget(self, *args): if 'content' in self.ids: return self.ids.content.add_widget(*args) return super(ShowcaseScreen, self).add_widget(*args) class ShowcaseApp(App): #code |
测试.kv
1 2 3 4 5 6 7 8 9 10 | <Testy>: orientation: 'vertical' Label: text: root.ttext ShowcaseScreen: name: 'LearnKanji' fullscreen: True #Some ref to <Testy> |
问题
我希望在 Testy() 中包含我的代码,因为我计划编写大量代码来针对单个屏幕中发生的情况,我不想让 ShowcaseScreen() 变得混乱,因为 ShowcaseScreen 是也适用于其他屏幕。
为了澄清,在 test.kv 我指的是变量 ttext。如果我没有创建类 Testy() 我会这样说:
1 2 3 4 5 | ShowcaseScreen: name: 'LearnKanji' fullscreen: True BoxLayout: text: root.ttext |
然后在 main.py 我需要把
1 2 | class ShowcaseScreen(Screen): ttext = 'Bla' |
但是,由于除了 Testy 之外的许多屏幕都使用类 ShowcaseScreen(),因此将所有屏幕的所有代码都放在这里会变得非常混乱。因此,我希望每个屏幕的代码在一个单独的类中。我认为这对于更大的代码项目来说是一种更好的方式。
那么在test.kv文件中调用ShowcaseScreen:后怎么引用呢?这样我就可以将用于 Testy 的代码放在 Testy() 中,并使我的文件和类更有条理。
后续问题:.py 和 .kv 交互 2 中的 Kivy 类
您可以使用
main.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition from kivy.properties import ObjectProperty class Testy(Screen): ttext = 'Screen 2' #other code class ScreenTwo(Screen): pass class Manager(ScreenManager): testy = ObjectProperty(None) screen_2 = ObjectProperty(None) class ShowcaseApp(App): def build(self): return Manager(transition=FadeTransition()) if __name__ =="__main__": ShowcaseApp().run() |
kv 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <Testy>: BoxLayout: Button: text: root.ttext on_press: root.manager.current ="screen_two" <ScreenTwo>: BoxLayout: Button: text:"Screen 1" on_press: root.manager.current ="testy_screen" <Manager>: id: screen_manager testy: testy screen_2: screen_2 Testy: id: testy name: 'testy_screen' manager: screen_manager ScreenTwo: id: screen_2 name: 'screen_two' manager: screen_manager |