Reputation: 117
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.
Upvotes: 5
Views: 2457
Reputation: 1938
I don't understand why there is no one tell you to use ACTIVEEVENT.
I don't know in older pygame version, but in windows 10, python 3.7.3, pygame 1.9.6, I can use this:
import pygame as pg
video = pg.display.set_mode((300,300))
running = True
while running:
for event in pg.event.get():
if (event.type == pg.ACTIVEEVENT):
if (event.gain == 1): # mouse enter the window
print("Welcome, cursor! :D ",
"Selamat datang, kursor! :D")
else: # mouse leave the window
print("Good bye, cursor! :( ",
"Sampai jumpa, kursor! :(")
elif (event.type == pg.QUIT):
running = False
pg.display.quit()
print("Bye! Have a nice day! ",
"Sampai jumpa! Semoga harimu menyenangkan! :)")
I've tested it. It works!
Upvotes: 2
Reputation: 143197
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()
Upvotes: 7
Reputation: 117
I did some testing...
if not bool(game.mouse.get_focused()):
print("Mouse has left (Method 1)")
and...
elif event.type == game.MOUSEMOTION:
checkFocus(event, self.canvas)
def checkFocus(e, display):
x, y = e.pos
MX, MY = display.get_size()
MX -= 1 # 0 - based
MY -= 1
if x <= 0 or y <= 0 or x >= MX or y >= MY:
print("Mouse has left (Method 2)")
and method 1 worked all of the time while method 2 only worked most of the time (Particularly around the max X and Ys [MX & MY])
Here's an actual log of me swinging my mouse around like a maniac...
Mouse has left (Method 1)
Mouse has left (Method 2)
Mouse has left (Method 1) <--
Mouse has left (Method 1) <--
Mouse has left (Method 2)
Mouse has left (Method 1)
As you can see, in just this short sample, method 1 works more often than method two.
Thank you to everyone who helped out!
Upvotes: 0