Search code examples
pythonuser-interfacepygamepython-2.xpygame-surface

How to make the "screen" variable accessible to all scripts in python/pygame


I am making my own UI in python 2 and pygame. I have my main script that creates the "screen" variable for the rendering surface in pygame.

How could I go about letting other python scripts access - and render on - the surface of another script?


Solution

  • You can achieve the desired effect by passing your screen variable as a parameter on any call of your extensions modules. The easiest way would be to design your modules as classes whose __init__ method accept the screen to render on:

    #extension1.py
    class Main(whatever_base_class):
        def __init__(self, screen, *args, **kwargs):
            self.screen = screen
            ...
        def Draw(self):
            #use self.screen to draw on screen.
    

    And from your main script:

    from extension1 import Main
    
    #define screen somehow
    ext1 = Main(screen, ...)
    ext1.Draw()
    

    If you can't or don't want to force the creation/modification of an __init__ in your extensions, you can either rely on a def setup(screen) method or directly pass the screen variable to the Draw method.