Eylon
Eylon

Reputation: 91

Get mouse click coordinates in Python turtle

I am trying to get the coordinates of a mouse click in the turtle screen, but my code isn't working. I guess this is related to time but I tried to add a 5 seconds delay but it didn't help.

Here is my code:

def get_mouse_click_coor(x,y):
   print [x,y]
turtle.onscreenclick(get_mouse_click_coor)

Please help me understand what is the problem with the code, thanks :)

Upvotes: 9

Views: 31222

Answers (2)

1nf1n17y
1nf1n17y

Reputation: 1

Why don't you just add a screen object and apply everything screen related to it?

Like so:

import turtle

def get_coor(x, y):
    print(x, y)

screen = turtle.Screen()

turtle.onscreenclick(get_coor)
screen.mainloop()

Basically your screen keeps up and running with the loop and the turtle does it's separate job ;)

Upvotes: 0

cdlane
cdlane

Reputation: 41872

Your code looks basically correct but let's make it complete:

import turtle

def get_mouse_click_coor(x, y):
    print(x, y)

turtle.onscreenclick(get_mouse_click_coor)

turtle.mainloop()

The above works -- all clicks on the window print the x & y coordinates to the console. Give it a try and let me know if it doesn't work for you.

I need to get the coordinates only one time

That's simple enough to accommodate, we simply turn off the click handler on the first click:

import turtle

def get_mouse_click_coor(x, y):
    turtle.onscreenclick(None)
    print(x, y)

turtle.onscreenclick(get_mouse_click_coor)

turtle.mainloop()

Upvotes: 15

Related Questions