python – Kivy – 屏幕管理器 – 访问其他类中的属性

前端之家收集整理的这篇文章主要介绍了python – Kivy – 屏幕管理器 – 访问其他类中的属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Kivy Screen Manager,我创建了两个Screens.在屏幕1中,我想在屏幕2中更改标签.我在我的代码中突出显示了有问题的区域:

我的test.ky:

#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#: import SettingsScreen screen


ScreenManager:
    MenuScreen:
    SettingsScreen:


<MenuScreen>:
    name: 'MenuScreen'
    BoxLayout:
        Button:
            text: 'Goto nn'
            on_press: 
                root.manager.current = 'SettingsScreen'
                root.change_text()


<SettingsScreen>:
    name: 'SettingsScreen'
    label_id: label_field
    BoxLayout:
        Label:
            id: label_field
            text: "to_be_changed"

和我的screen.py

from kivy.app import App
from kivy.uix.Boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager,Screen


class MenuScreen(Screen):
    def change_text(self):
        pass
        # HERE: something like
        # root.SettingsScreen.label_field.text = 'new text'


class SettingsScreen(Screen):
    pass


class TestApp(App):
    pass

TestApp().run()

任何帮助是极大的赞赏!
谢谢,尼科

解决方法

这个怎么样:

当您按下MenuScreen上的按钮时,它会在其自身上设置一个属性,其中包含您要放入SettingsScreen标签中的文本.然后在菜单屏幕中为kv文件分配一个id值,该值用于引用此属性.例:

main.py

class MenuScreen(Screen):
    text = StringProperty('')
    def change_text(self):
        self.text = "The text you want to set"
        self.manager.current = "SettingsScreen"

class SettingsScreen(Screen):
    label_text = StringProperty('')

kv文件

ScreenManager:
    id: screen_manager
    MenuScreen:
        id: menu_screen
        name: 'MenuScreen'
        manager: screen_manager
    SettingsScreen:
        name: 'SettingsScreen'
        manager: screen_manager
        label_text: menu_screen.text

<MenuScreen>:
    BoxLayout:
        Button:
            text: 'Goto nn'
            on_press:
                root.change_text()

<SettingsScreen>:
    BoxLayout:
        Label:
            text: root.label_text

正如您所看到的,我在屏幕管理器中设置了屏幕的名称和ID在kv文件中,因为这是我通常要做的工作.

猜你在找的Python相关文章