1
votes

I want to obtain coordinates of mouse position at the time when the mouse button is pressed. I'm using the following code to try to achieve that:

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos

My problem is when I move the mouse just after clicking, event.pos gives me the new cursor position instead of the coordinates of where I actually clicked. How do I set mouse_pos to the actual coordinates of the click?

1
Is move mouse just after clicking different then dragging in your context - Laschet Jain
If you use mouse_pos = event.pos, mouse_pos will contain the actual coordinates of the click. Maybe you overwrite it elsewhere in your code? - sloth
@udhy Yes, I release the mouse button and then move. - Brian Cheng
@sloth No, I didn't find it overwritten elsewhere in the code. - Brian Cheng
Try making a small program and run this code, does this still gives an error. - Laschet Jain

1 Answers

0
votes

Although this thread was asked 4 months ago if your still looking for the answer here it is...

In your loop you are using the wrong command to get the mouse position. Instead of using this...

mouse_pos = event.pos

Use this...

mouse_pos = pygame.mouse.get_pos()

This command will grab the current mouse location when called, and return it as a tuple like this (x,y).

I hope this helps you with your issue.