Center a GLFW Window at Screen using Python

Hi,

I share the example for beginners how to center a window at screen because I did not find it by myself in the Internet and I wrote it from scratch. I hope it will useful for someone.

import glfw

if not glfw.init():
    raise Exception("Failed to initialize the GLFW library")

window = glfw.create_window(400, 300, "My Centered Window", None, None)
monitor = glfw.get_primary_monitor()
pos = glfw.get_monitor_pos(monitor)
size = glfw.get_window_size(window)
mode = glfw.get_video_mode(monitor)
print(int((mode.size.height - size[1]) / 2))
glfw.set_window_pos(
    window,
    int(pos[0] + (mode.size.width - size[0]) / 2),
    int(pos[1] + (mode.size.height - size[1]) / 2))

if not window:
    glfw.terminate()
    raise Exception("Failed to create the GLFW window")

glfw.make_context_current(window)

while not glfw.window_should_close(window):
    glfw.poll_events()
    glfw.swap_buffers(window)

glfw.terminate()

3 Likes

Many thanks for the code example!

1 Like