AlgoRythm AlgoRythm - 18 days ago 5
Python Question

Detect if mouse has left Pygame window

I'm writing a small Pygame script and I need to know if the mouse has left the Pygame window

I don't know how else to explain it. It seems simple, but I can't find a solution anywhere.

Answer

pygame.mouse.focus() gives 0 when mouse leaves window (at least in Linux)

#!/usr/bin/env python3

import pygame

pygame.init()
screen = pygame.display.set_mode((800,600))

is_running = True
while is_running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False

    print(pygame.mouse.get_focused())

pygame.quit()