我正在使用 KivyMD 并希望使用“on_pre_enter”方法在第二个屏幕中刷新数据。我正在尝试从屏幕类“on_pre_enter”方法访问标签 ID,但没有成功。
我可以从“MainApp”类访问标签 ID,但无法从“Second_Screen”类访问它。
主应用程序.py
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen
class MainApp(MDApp):
def __init__(self, **kwargs):
self.title = "My Material Application"
self.theme_cls.primary_palette = "Blue"
super().__init__(**kwargs)
def on_start(self):
self.root.ids.main_screen_label.text = "Main Screen Updated"
def build(self):
self.root = Builder.load_file("app.kv")
class Second_Screen(Screen):
def on_pre_enter(self):
MainApp.ids.second_screen_label = "Second Screen Updated"
pass
if __name__ == "__main__":
MainApp().run()
应用.kv
NavigationLayout:
MDNavigationDrawer:
NavigationDrawerSubheader:
text: "Menu:"
NavigationDrawerIconButton:
icon:'battery'
text: "Main Screen"
on_release:
screen_manager.current = "main_screen"
NavigationDrawerIconButton:
icon:'battery'
text: "Second Screen"
on_release:
screen_manager.current = "second_screen"
BoxLayout:
id: box1
orientation: 'vertical'
MDToolbar:
title: "My App"
md_bg_color: app.theme_cls.primary_color
left_action_items:
[['menu', lambda x: app.root.toggle_nav_drawer()]]
ScreenManager:
id: screen_manager
Screen:
name: "main_screen"
BoxLayout:
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: 'vertical'
MDLabel:
id: main_screen_label
text: "Main Screen Default"
Second_Screen:
name: "second_screen"
FloatLayout:
id: float
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: 'vertical'
MDLabel:
id: second_screen_label
text: "Second Screen Default"
我也尝试过使用:
class Second_Screen(Screen):
def on_pre_enter(self):
self.ids.second_screen_label.text = "Second Screen Updated"
pass
启动后我收到以下错误:
self.ids.second_screen_label.text = "Second Screen Updated"
File "kivy\properties.pyx", line 863, in
kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
从屏幕类访问 KV 文件中定义的 id 的正确方法是什么?