1

How to get variable from one class to another class in python

class WelcomeScreen(Screen): #welcomeScreen subclass
    def __init__(self, **kwargs): #constructor method
        super(WelcomeScreen, self).__init__(**kwargs)
        welcomePage = FloatLayout()
        box = BoxLayout(orientation='vertical', size_hint=(0.4, 0.3),
                                       padding=8, pos_hint={'top': 0.5, 'center_x': 0.5})
        self.cameraObject = Camera(play=False)  ## WANT TO USE THIS VARIABLE IN OTHER CLASS
        self.cameraObject.play = True
        self.cameraObject.resolution = (700, 400)
        self.add_widget(self.cameraObject)

class FunctionScreen(Screen):  
    def __init__(self, **kwargs): 
        super(FunctionScreen, self).__init__(**kwargs) #init parent

        functionPage = FloatLayout()
        functionLabel = Label(text='what functions to use',
                          halign='center', valign='center', size_hint=(0.4,0.2), pos_hint={'top': 1, 'center_x': 0.5})
        img = self.cameraObject ## HERE I WANT TO USE 'self.cameraObject' VARIABLE

How to get "self.cameraObject" from class WelcomeScreen(Screen) to class FunctionScreen(Screen)? Thanks in advance :)

Submitted July 28th 2020 by Admin

Answers
0

I think that your cameraObject should belong to the Screen class or some intermediate abstraction, as it is used by both sub-classes. In this way, the superclass instantiates the cameraObject and any subclass can use it.

Admin | 1 year ago


0

You need to take your cameraObject instance out of your classes and pass the single instance of cameraObject to them:

 cameraObject = Camera(play=False) cameraObject.play = True cameraObject.resolution = (700, 400) WelcomeScreen(foo,bar,cameraObject) FunctionScreen(foo,bar,cameraObject)

It's that or create the camera outside of your classes:

cameraObject = Camera(play=False) cameraObject.play = True
cameraObject.resolution = (700, 400) class WelcomeScreen(Screen): #welcomeScreen subclass def __init__(self, **kwargs): #constructor method super(WelcomeScreen, self).__init__(**kwargs) ... self.add_widget(cameraObject) class FunctionScreen(Screen): def __init__(self, **kwargs): super(FunctionScreen, self).__init__(**kwargs) #init parent ... img = cameraObject 

I also think this might be helpful on the same camera for multiple screens in kivy.

Admin | 1 year ago



Relevant Questions