turtle.onclick() function in Python

The turtle.onclick() function binds a function to a mouse-click event on the turtle. The function will be called whenever the turtle is clicked.

Syntax: turtle.onclick(fun, btn=1, add=None)
Parameters: fun – a function with two arguments (x, y coordinates of the click); btn – mouse button number (default 1, left click).

Let us see an example to implement the turtle.onclick() function in Python:

Demo31.py

# turtle.onclick() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

def click_handler(x, y):
    t.goto(x, y)
    print(f"Clicked at ({x}, {y})")

t.onclick(click_handler)  # Bind click event to handler

window.mainloop()

The following is the output:

turtle.onclick() function in Python

In the above code, we followed the below steps:

  1. Import the module: import turtle loads Python’s turtle graphics library.
  2. Create the screen: window = turtle.Screen() opens the drawing window.
  3. Create the turtle: t = turtle.Turtle() creates the turtle (your pen).
  4. Define the click handler:
    • Function: def click_handler(x, y):
    • Move: t.goto(x, y) moves the turtle to the clicked coordinates (it will draw a line if the pen is down, which is the default).
    • Log: print(f”Clicked at ({x}, {y})”) prints the click location to the console.
  5. Bind the event: t.onclick(click_handler) attaches the handler to mouse clicks on the turtle itself (not the whole canvas). For clicks anywhere on the screen, you’d use window.onscreenclick(click_handler) instead.
  6. Start event loop: window.mainloop() starts the GUI event loop so the window stays open and responds to clicks.

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

turtle.clear() function in Python
turtle.onkey() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment