In this piece of code, I've created a program using the Turtle Module for Python, which I heard was built with Tkinter. This working code will make the turtle say "Ah!" when you click on it, then teleport. What perplexes me the most is the t.onclick() method. How does it manage to keep listening for clicks on the turtle while allowing the rest of the code to run, unlike the input() function, which waits for the user to enter an input before proceeding?
Additionally, how does an event handler work in Python? Does it constantly check for clicks in the background with some sort of forever loop? Is there a mechanism that allows it to stay idle and somehow activate when a click is received? Or is there something else entirely that makes it work the way it does?
from turtle import *
from time import sleep
from random import randint
t = Turtle()
t.color("red")
t.penup()
t.shape("turtle")
t.speed(100)
t.points = 0
w = 200
h = 150
def rand_move():
t.goto(randint(-w, w), randint(-h, h))
def catch(x, y):
t.write("Ah!", font=("Arial", 14, "normal"))
t.points = t.points + 1
rand_move()
t.onclick(catch)
while t.points < 3:
sleep(1.5)
rand_move()
t.write("WOW! You're good at catching me!", font=('Arial', 16, 'bold'))
t.hideturtle()
I have tried looking up the Turtle source code but failed to decipher it, and even googled quite a number of sites, but none seem to be specific enough to this question. Any help in clearing this up will be greatly appreciated!