Using turtle.onscreenclick to find coordinates of a mouse click

Question:

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()
Asked By: Derek Bischoff

||

Answers:

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

Answered By: en_Knight

It’s actually alot easier to detect where you clicked it. Here’s the code:

from turtle import *
mouseclickx = 0
mouseclicky = 0
def findcoords(x,y):
    print(x)
    print(y)
    mouseclickx = x
    mouseclicky = y
onscreenclick(findcoords,1)

EDIT:
That doesn’t work… well idk but it should be something like that :/ if you want a thing so it goes where you click, its one line;onscreenclick(goto,1)

Answered By: arkanon
from turtle import Turtle, Screen

screen = Screen()

def get_mouse_click(x, y):   

   print(x, Y)

screen.onscreenclick(get_mouse_click)

screen.mailoop()
Answered By: user20005724