7

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 :)

cdlane
  • 40,441
  • 5
  • 32
  • 81
Eylon
  • 71
  • 1
  • 1
  • 3
  • 1
    Please consider marking @cdlane 's answer as accepted (check mark on the left) since it worked for you. – glhr Apr 04 '19 at 02:01

2 Answers2

10

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()
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • It worked but it is looping, I need to get the coordinates only one time... – Eylon Mar 19 '17 at 08:49
  • @Eylon, I've augmented my answer to show how to make only respond to one click. – cdlane Mar 19 '17 at 17:59
  • Thank you but I need the code to continue after the click and it gets one click and then stuck. How can I make it continue after the click? @cdlane – Eylon Mar 19 '17 at 18:08
  • (it doesn't actually stuck, it's just keep looping because of the turtle.mainloop(), and i i remove that line, it doesn't get the coordinates – Eylon Mar 19 '17 at 18:15
  • @Eylon, your terms **looping** and **stuck** aren't really descriptive of what's going on. The `mainloop()` call is required and is what allows things like mouse clicks to be processed. If you want **something** to happen after the click, put a call to that **something** in the click handler. Or have the click handler fire off a timer event. Regardless, if it's not doing what you want, you need to go back to your question and do a more detailed job of describing what you do want. As it is, the code does what you asked for it to do. – cdlane Mar 20 '17 at 04:03
  • i added a call to the next function in the get_mouse_click_coor and it is now working. thank you!! – Eylon Mar 21 '17 at 07:06
0

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 ;)