首页 > 解决方案 > 有没有办法在 Kivy 中使用 id 访问其他类对象?

问题描述

我正在制作一种方法来更改我的 Kivy 应用程序中的语言。

我正在尝试使用ids从其他类访问对象。

我的 .py 代码的一部分:

    class SettingsScreen(Screen):
        def change_langg(self):

           #MainMenu screen
           self.main = MenuScreen()
           self.exit_but = self.main.ids['exit']
           #Settings screen
           self.back1_but = self.ids['back1']
           self.lang_but = self.ids['language']
           self.fullscr_but = self.ids['fullscr']

           if self.lang_but.text == 'Бг':

              #Main menu screen
               self.exit_but.text = 'Изход'
               #Settings screen
               self.back1_but.text = 'Назад'
               self.fullscr_but.text = 'Цял екран'
               self.lang_but.text = 'En'

           elif self.lang_but.text == 'En':
              #Main menu screen
              self.exit_but.text = 'Exit'
              #Settings screen
              self.back1_but.text = 'Back'
              self.fullscr_but.text = 'Fullscreen'
              self.lang_but.text = 'Бг'

我希望文本在两个屏幕中都会发生变化,但它只会在“设置”屏幕中发生变化。正如我上面提到的,我没有任何错误,所有 id 都是正确的。你有什么建议吗?

标签: pythonkivy

解决方案


我有一个即使在屏幕显示后也能工作的解决方案。代码和注释应该是不言自明的,否则在不清楚的部分与我联系

othrscrn = '' #global variable where the memory location of the other screen can be saved

    class OtherScreen(Screen):
        def __init__(self, *args): #init method to run immediately the code is started
            super(OtherScreen, self).__init__(*args)
            global othrscrn #declaring variable 'othrscrn' a global variable
            othrscrn = self #saving the class' memory location to global variable 'othrscrn'

    class Settings(Screen):
            def change_lang(self):
                global othrscrn #accessing the variable 'othrscrn'
                x = othrscrn #instanciating the class as a new variable x
                lan = x.ids['language'] #acessing the class' ids using its ids
                lan.text = ''#any chnage you want to implement

推荐阅读