Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if mouse is outside pygame window

Tags:

python

pygame

I was running a game in pygame, and I discovered a flaw. The way I coded it, if the mouse went outside of the window, the game started to go around in circles. When you get pygame.mouse.get_pos(), it will return the last value the mouse was detected in the window, but other wise no indication that the mouse has left the window. So, is there any way to check if the mouse has stopped hovering over the pygame window, and has left it?

like image 385
User 12692182 Avatar asked Oct 15 '25 08:10

User 12692182


1 Answers

A simple answer to this would be to use the pygame.mouse.get_focused() function. This returns 0 when the mouse isn't focused on the screen. So if you wanted to check if the mouse was outside the window, you could simply do

mouseFocus = pygame.mouse.get_focused()

During the main loop and have an if statement checking if the mouse has left the screen.

if mouseFocus == 0:
    print("mouse is out of screen.")

Hope this helps

like image 108
Stellan Avatar answered Oct 18 '25 07:10

Stellan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!