While trying to port turtle to different backend (not Tkinter), I faced the following problem
from turtle import *
onscreenclick(lambda x,y:print(x,y))
while True:
#a=heading() # option 1. clicks are not reported
setheading(0) # option 2: clicks are reported
Notice that mainloop() is not called. Although I know it's a bad habit to use while True loops in turtle programming, I don't understand why this program works with option 2. What is the magick that allows events to be dispatched and propagated outside the event loop?
In option 1, you're asking about the turtle, in option 2, you're asking the turtle to do something. My guess is in, the first case, there are no handoffs to the event handler to check for the clicks. In the second case, handoff is being made to the event handler as part of doing something.
This behaves the same way on standard turtle (with Tkinter), where the first option never prints. Let's make both cases do something by adding a call to
update()
.This works for both cases under standard turtle, as now we're handing off to the event hander on every iteration. This is an example of why
while True
isn't just a bad habit, but a bad idea. In standard turtle, I would write this using a timer event: