pythonpgzero

Center window of a Pygame Zero game


I am using the easy-to-use Python library pgzero for programming games.

How can I center the game window? )It always opens at a random position...

import pgzrun

TITLE = "Hello World"

WIDTH  = 800
HEIGHT = 600

pgzrun.go()

Note: I am using the runtime helper lib pgzrun to make the game executable without an OS shell command... It implicitly imports the pgzero lib...

Edit: pgzero uses pygame internally, perhaps there is a way to center the window using the pygame API...


Solution

  • You can use os.environ['SDL_VIDEO_CENTERED'] = '1'

    This line of code tries to center your window the best it can.

    Try this:

    import pgzrun
    import os
    
    TITLE = "Hello World"
    
    WIDTH  = 800
    HEIGHT = 600
    
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pgzrun.go()