在screenmanager对象中引用ID

2024-06-12 19:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着了解一下screenmanager,特别是引用其中的对象。在

我用这个来设置一个值:

class Widgets(Widget)
    pass

w = Widgets()
w.ids.MyTitle.text = 'something'

现在我有了这个:

^{pr2}$

我现在如何引用我的标题?我试过各种组合,比如:

sm.ids.main.MyTitle.text =
sm.main.MyTitle.text =
sm.main.ids.MyTitle.text = 

。。。。但没有得到它!有人能让我摆脱痛苦吗?有没有一种简单的方法可以浏览sm对象或者迭代它?在

编辑:添加最小运行版本:

在最小.kv公司名称:

# File name: minimal.py
#:kivy 1.8.0

<Widgets>
    Button:
        id: MyTitle
        text: 'hello'

<SettingsScreen>:
    Button:
        id: Other
        text: 'settings'

在最小.py公司名称:

from kivy.uix.widget import Widget
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.app import App


class Widgets(Screen):
    pass

class SettingsScreen(Screen):
    pass

class myApp(App):

    def build(self):
        return sm

    def on_start(self):
        global sm
        sm.ids['main'].ids['MyTitle'].text = 'changed' # <-- this fails

Builder.load_file("minimal.kv")

sm = ScreenManager()
sm.add_widget(Widgets(name='main'))
sm.add_widget(SettingsScreen(name='settings'))

if __name__ == '__main__':
    myApp().run()

Tags: textnamefromimportidsmainbuttonpass
2条回答

根据the documentation,您可以访问id,就像访问任何字典键一样:

widget.ids['MyTitle']

因为^{}本身是从Widget派生的,并且给定的小部件维护a list of widgets it is aware of,所以您可能需要类似以下内容:

^{pr2}$

然而,如果没有Minimal, Complete, and Verifiable Example,这很难说。你可以做的一件事是:

for id in sm.ids:  # Iterate through all widgets in ids
    print(id)  # Get the string representation of that widget

作为旁注,这:

class Widgets(Screen)
    pass

。。。可能会引起混淆,因为您使用Widgets(通过中间类Screen)扩展{}。OOP建议类的子类应该是类的更具体的形式。因此,ScreenWidget类型。但是Widgets实际上是Widgets的一个数。在

要从ScreenManager获取屏幕,请使用^{}

sm.get_screen('main').ids.MyTitle.text = 'changed'

此外,您可以构建应用程序,以便: kv文件:

^{pr2}$

在python文件中:

sm=Builder.load_file(..)

class my12App(App):
    def build(self):
        return sm

    def on_start(self):
        self.root.get_screen('main').ids.MyTitle.text = 'changed'

相关问题 更多 >