获取在另一个屏幕中声明的变量

时间:2018-04-25 11:25:57

标签: python kivy

我正在开发一个简单的Kivy GUI应用程序。我想要做的是我想要访问一个对象' obj_random'班级' CL_Random'从第二个屏幕(不创建它)。我只是不知道如何在一个屏幕上声明访问不同的屏幕。

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
#from kivy.uix.boxlayout import BoxLayout
#from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty


class CL_FirstWindow(Screen):
    def change_screen(self):
        obj_random = CL_Random()
        self.parent.current = 'second_window'

class CL_SecondWindow(Screen):
    scond_prop = ObjectProperty(None)
    def change_screens(self):
        self.parent.current = 'first_window'

class ScreenManagement(ScreenManager):
    pass

class CL_Random:
    def __init__(self):
        self.x = 5

presentation = Builder.load_file("rough2.kv")

class app(App):
     def build(self):
        return presentation


obj_app = app()
obj_app.run()

rough2.kv

ScreenManagement:
    CL_FirstWindow:
    CL_SecondWindow:

<CL_FirstWindow>:
    id: first_window_id
    name: 'first_window'
    FloatLayout:
        Button:
            text: 'Button1'
            size_hint: 0.3, 0.12
            pos_hint: {'x':0.1,'y':0.6}
            on_release: root.change_screen()
<CL_SecondWindow>:
    id: second_window_id
    name: 'second_window'
    FloatLayout:
        Button:
            text: 'Button2'
            size_hint: 0.3, 0.12
            pos_hint: {'x':0.1,'y':0.6}
            on_release: root.change_screens()
        Label:
            id: second_label_id
            text: 'SECOND SCREEN'
            pos_hint: {'x': 0.20, 'y':0.8}
            size_hint: 1, 0.1
            font_size: 35
            halign: 'left'
            valign: 'middle'
            text_size: self.size

Thnks

1 个答案:

答案 0 :(得分:0)

要访问在类中声明的变量,第一件事是该变量必须是类的属性,以便范围更大,但在您的情况下,变量是本地的,并且当它变量时它将被消除完成执行功能。

另一方面,解决方案基于通过ScreenManager访问其他屏幕,并让对象访问该属性,我们使用get_screen()方法:

CL_SecondWindow --> ScreenManager --> CL_FirstWindow --> obj_random
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.properties import ObjectProperty


class CL_FirstWindow(Screen):
    def change_screen(self):
        self.obj_random = CL_Random()
        self.manager.current = 'second_window'

class CL_SecondWindow(Screen):
    scond_prop = ObjectProperty(None)
    def change_screens(self):
        first_screen = self.manager.get_screen('first_window')
        print(first_screen.obj_random.x)

        self.parent.current = 'first_window'

class ScreenManagement(ScreenManager):
    pass

class CL_Random:
    def __init__(self):
        self.x = 5

presentation = Builder.load_file("rough2.kv")

class app(App):
     def build(self):
        return presentation


obj_app = app()
obj_app.run()