turtle.onclick() function in Python
turtle.onclick() function binds a function to mouse-click events on the turtle or canvas. When the user clicks, the specified function executes with the clickâs (x, y) coordinates.
Syntax :
turtle.onclick(fun, btn=1, add=None)
Parameters:
- fun : Function with two arguments (x, y) for click coordinates.
- btn : Mouse button number (default = 1 â left button).
- add : True adds a new binding, False replaces the old one.
Returns: This function returns None.
Example
Example 1 : Move on click
import turtle
def fxn(x, y):
turtle.right(90)
turtle.forward(100)
turtle.speed(1)
turtle.forward(100)
turtle.onclick(fxn)
turtle.done()
Output :

Explanation:
- fxn(x, y) function executes when turtle is clicked.
- turtle.right(90) turns turtle 90° right.
- turtle.forward(100) moves turtle forward 100 units.
- turtle.onclick(fxn) binds click event to function.
Example 2 : Go to click position
import turtle
wn = turtle.Screen()
def fxn(x, y):
turtle.goto(x, y)
turtle.write(str(x) + "," + str(y))
wn.onclick(fxn)
wn.mainloop()
Output :

Explanation:
- fxn(x, y) runs on mouse click with coordinates.
- turtle.goto(x, y) moves turtle to click position.
- turtle.write(...) prints coordinates on canvas.
- wn.onclick(fxn) binds click event to screen.
- wn.mainloop() keeps window active.