pythonpython-3.xarcade

Centering a window in Arcade with Python 3


I am coding a game using the arcade module and don't know how to centre the window so it appears directly in the middle of my screen rather than in the top left. My current code for creating the window is as follows:

class MyGame(arcade.Window):
    def __init__(self, width, height):
        super().__init__(width, height, "Pong!")
        arcade.set_background_color(arcade.color.BLACK)

After completing the methods for this class, my main function is:

def main():
    """ Main method """
    game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
    arcade.run()

Edit: Re-worded a couple of sentences to better explain the issue


Solution

  • I couldn't find this easily anywhere so here is what I figured out, in case anyone else needs this:

    The arcade module is written over the pyglet module, so you can use the pyglet class pyglet.canvas.Screen to find the screen size and then use arcade.Window.set_location(x, y) to set the window position. So first import pyglet, then you can get the Screen that you're using from the current Display:

    import pyglet
    
    # set up the screen
    SCREEN_NUM = 0
    SCREENS = pyglet.canvas.Display().get_screens()
    SCREEN = SCREENS[SCREEN_NUM]
    

    (SCREEN_NUM can be changed if you're using multiple monitors.)

    Then inside MyGame, you can add this method:

    def center_on_screen(self):
        """Centers the window on the screen."""
        _left = SCREEN_WIDTH // 2 - self.width // 2
        _top = SCREEN_HEIGHT // 2 - self.height // 2
        self.set_location(_left, _top)
    

    Simply call MyGame.center_on_screen() during initialization or any time the game window needs to be centered.