turtle.onscreenclick() function in Python

The turtle.onscreenclick() function binds a function to a mouse-click event anywhere on the screen. The function will be called with the click’s coordinates.

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

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

Demo33.py

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

import turtle

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

def screen_click(x, y):
    t.goto(x, y)
    print(f"Screen clicked at ({x}, {y})")

window.onscreenclick(screen_click)  # Bind screen click event

window.mainloop()

The following is the output:

turtle.onscreenclick() 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 you’ll control.
  4. Define screen-click handler:
    • def screen_click(x, y): defines a function that receives the click coordinates.
    • t.goto(x, y) moves the turtle to the clicked position (it draws a line if the pen is down).
    • print(f”Screen clicked at ({x}, {y})”) logs the coordinates in the console.
  5. Bind click event: window.onscreenclick(screen_click) attaches the handler to mouse clicks anywhere on the screen (canvas), passing the click’s x and y coordinates.
  6. Run event loop: window.mainloop() keeps the window open and responsive to clicks until it’s closed.

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.onkey() function in Python
turtle.onrelease() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment