本文介绍了Kivy-屏幕管理器-访问其他类中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Kivy屏幕管理器,创建两个屏幕.在屏幕1中时,我想在屏幕2中更改标签.我在代码中突出显示了有问题的区域:

Using the Kivy Screen Manager, I create two Screens. Whilst being in screen 1, i want to change a label in screen two. I highlight the problematic area in my code:

我的 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()

任何帮助将不胜感激!谢谢Nico

Any help is greatly appreciated!Thanks, Nico

推荐答案

这是怎么回事:

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

When you press the button on MenuScreen, it sets an attribute on itself containing the text you want to put in the SettingsScreen Label. Then the MenuScreen is assigned an id value in the kv file, which is used to reference this attribute. Example:

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

如您所见,我在kv文件中的ScreenManager本身下设置了屏幕的名称和ID,因为这通常是我要做的工作.

As you can see, I set the names and id of the screens under ScreenManager itself in the kv file, as this is what I would usually do to make this work.

这篇关于Kivy-屏幕管理器-访问其他类中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 15:38