Derek Bischoff Derek Bischoff - 3 months ago 17
Python Question

Using turtle.onscreenclick to find coordinates of a mouse click

I simply want to use the turtle method onscreenclick to find the coordinates of a mouse click. Currently, I have a grid on which I am playing Othello. I already have the algorithm to convert the raw coordinates to specific grid coordinates that can be interpreted by the game. I cannot seem to get the onscreenclick method working. On the docs, it says to use a 'fun' function with two arguments. I believe I have this, but it is not working. I am a beginner with python and turtle so any help would be appreciated :)

import turtle

xclick = 0
yclick = 0

def getcoordinates():
turtle.onscreenclick(modifyglobalvariables())

def modifyglobalvariables(rawx,rawy):
global xclick
global yclick
xclick = int(rawx//1)
yclick = int(rawy//1)
print(xclick)
print(yclick)

getcoordinates()

Answer

You got so close!

import turtle

xclick = 0
yclick = 0

def getcoordinates():
    turtle.onscreenclick(modifyglobalvariables) # Here's the change!

def modifyglobalvariables(rawx,rawy):
    global xclick
    global yclick
    xclick = int(rawx//1)
    yclick = int(rawy//1)
    print(xclick)
    print(yclick)

getcoordinates()

Catch the change? Syntactically, remove the parentheses after modfiyglobalvariables. What you want is to pass the function, what you are doing is passing the output of the function.

If you ran the code, you would get an exception (TypeError) saying you haven't passed the correct arguments; that's because it's trying to actually call modifyglobalvariables. Reduced, what you wanted was

bind_to_mouseclick( my_function )

In which case, at each mouse click, my_function will be called. At that point, it may or may not have the correct arguments supplied. Instead you said

bind_to_mouseclick( my_function() )

Python evaluates my_function and binds the result of the call to the mouse click. If my_function happens to return a function, that's great (maybe what we intended). If it returns an integer or a string, no good. The key is the exception, as noted above; if the function had required no arguments, this may have been subtler to detect