How to get the mouse position in pygame

We can get the mouse position with pygame.mouse.get_pos()



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code and hover your mouse on the pygame window. This will print mouse position.

We can me this interesting by moving a rectangle based on the mouse position.

We just have to know the mouse position in the coordinate ( x,y)

In the previous program print(mouse_postion) shows the tuble value

so we can get the x, y value by

mouse_position=pygame.mouse.get_pos()
x,y=mouse_position

As we get the x,y value it will be easy to apply in the next example



import pygame,sys
from pygame.locals import*
pygame.init()
screen=pygame.display.set_mode((400,400))

game_running=True
while game_running:
	for event in pygame.event.get():
		if event.type==QUIT:            
			pygame.quit()
			sys.exit()
	mouse_position=pygame.mouse.get_pos()
	x,y=mouse_position
	screen.fill((255,255,255))
	pygame.draw.rect(screen,(100,100,100),(x,y,60,40),5) #rect(surface,color,(x,y,height,width)
	print(mouse_position)
	pygame.display.update()
    
    
    

Run this code you will find that rectangle is attach to the mouse position