Reputation: 54
I'm trying to make python detect the position of the mouse. My code:
import pygames
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
WHITE = (255,255,255)
screen.fill(WHITE)
pygame.mouse.set_pos([100,100]) #I didn't move my mouse so [0,100] should be the output
x_y = pygame.mouse.get_pos()
#I then run this program. Here is the output:
(0, 0)
I don't know what's wrong. Why are the coordinates wrong?
Upvotes: 3
Views: 281
Reputation: 20438
I don't know why it shows the wrong coordinates, but it seems to happen only if there's another window (in this case the IDLE window) in front of the pygame window. If the pygame window is selected/focussed and you set the mouse pos, pygame.mouse.get_pos()
will return the correct coordinates. Try to set the mouse pos in an event loop (press the s key):
import pygame
pygame.init()
size = (800, 500)
screen = pygame.display.set_mode(size)
pygame.mouse.set_pos([100,100])
WHITE = (255,255,255)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
pygame.mouse.set_pos([100,100])
print(pygame.mouse.get_pos())
screen.fill(WHITE)
pygame.display.flip()
clock.tick(30)
pygame.quit()
Or run the program in the command-line/terminal.
Upvotes: 1