![](/img/trans.png)
[英]Using ScreenManager in Kivy (Python) with several .py screens
[英]How to reference objects in other screens using kivy screenmanager
我正在嘗試更新另一個屏幕中存在的字段,但沒有成功。 當有人可以告訴我我在做什么錯時,我會感到非常高興。
myscreenskv.py:
style = r'''
# File: myscreenskv.py
#: import myscreens myscreens
<ScreenManagement>:
MainScreen:
Screen1:
Screen2:
<MainScreen>:
name: 'main'
mainlog:mainlog
id: scrmain
BoxLayout:
orientation: "vertical"
Label:
text: "Main"
Label:
id: mainlog
Button:
text: "go to screen 1"
on_press:
app.root.current = "screen1"
root.action1()
Button:
text: "go to screen 2"
on_press:
app.root.current = "screen2"
root.action2()
<Screen1>:
name: 'screen1'
sc1log:sc1log
id: scr1
BoxLayout:
orientation: "vertical"
Label:
text: "Screen1"
Label:
id: sc1log
Button:
text: "go to main screen"
on_press: app.root.current = "main"
Button:
text: "go to screen 2"
on_press: app.root.current = "screen2"
<Screen2>:
name: 'screen2'
id: scr2
sc2log:sc2log
BoxLayout:
orientation: "vertical"
Label:
text: "Screen2"
Label:
id: sc2log
Button:
text: "go to main screen"
on_press: app.root.current = "main"
Button:
text: "go to screen 1"
on_press: app.root.current = "screen1"
'''
.py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from myscreenskv import style
class MainScreen(Screen):
def __init__(self, **kwargs):
super(MainScreen, self).__init__(**kwargs)
def action1(self):
self.ids.scr1.sc1log.text = 'Coming from main'
def action2(self):
self.ids.scr2.sc2log.text = 'Coming from main'
class Screen1(Screen):
def __init__(self, **kwargs):
super(Screen1, self).__init__(**kwargs)
def action1(self):
self.ids.main.mainlog.text = 'Coming from screen1'
def action2(self):
self.ids.scr2.sc2log.text = 'Coming from screen1'
class Screen2(Screen):
def __init__(self, **kwargs):
super(Screen2, self).__init__(**kwargs)
def action1(self):
self.ids.main.mainlog.text = 'Coming from screen2'
def action2(self):
self.ids.scr1.sc1log.text = 'Coming from screen2'
class MyscreensApp(App):
def build(self):
Builder.load_string(style)
sm = ScreenManager()
sm.add_widget(MainScreen())
sm.add_widget(Screen1())
sm.add_widget(Screen2())
sm.current = 'main'
return sm
if __name__ == '__main__':
MyscreensApp().run()
您正在嘗試訪問ids
字典,這很好,但是在完全不同的實例中,這就是此錯誤的原因:
AttributeError: 'super' object has no attribute '__getattr__'
您需要訪問正確的實例,才能訪問其屬性,在這種情況下,您需要訪問ScreenManager
,以訪問其screens
屬性(實例列表),例如,可以從中進行所需的編輯文本:
MainScreen.action1():
self.manager.screens[1].sc1log.text = 'Coming from main'
# no ids, because you put it into a variable before
要了解它為什么起作用,讓我們看一下小部件樹:
<MainScreen>:
id: scrmain
BoxLayout:
Label:
Label:
id: mainlog
Button:
Button:
這里的ids
是MainScreen
中的字典,可從MainScreen().ids
(一個實例)訪問,這是輸出:
{'mainlog': <WeakProxy to <kivy.uix.label.Label object at 0x12345678>>}
這意味着您不能真正將根窗口小部件分配給它自己的字典-至少不是這種方式+仍然毫無意義,因為您只能調用root
,它為您提供了根窗口小部件的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.