Every GUI (or game) runs special loop called "mainloop" or "even loop" which does all the job. Pyglet starts this loop with run()
.
Pyglet has special queue for information called "events"
When you press button then system adds to queue information "event_keydown" with pressed key; when you click mouse then system adds to queue information "event_mousebuttondown" with pressed button and mouse position; etc.
Other functions in Pyglet can also add information to queue so mainloop can get this information from queue but later. ie. when you click button then button can add to queue "even_draw" because it needs to be redrawed with new color, and mainloop will do this but later.
@window.event
adds function name to special list/dictionary assigned to event name ie.
special_dict["event_draw"] = on_draw
"mainloop" checks all the time queue with events. When it get "event_draw" then it check "special_dict" to get function name which it has to execute - and it get "on_draw" and executes "on_draw()"
When you click mouse then system puts in queue "event_mousebuttondown". When mainloop get this "event_mousebuttondown" from queue then it sends it to all widgets and every widget checks if it was clicked. If some widget was clicked and have to change color/shape/etc. then it can put "event_draw" in queue. Later "mainloop| can get "event_draw" from queue and execute "on_draw" to redraw window.
Because "mainloop" checks queue all the time and does it fast (and all functionw assigned to events are short) then it looks like everything is done at the same time, and all widgets work at the same time - like they use threading (but they don't use threads). When you put sleep()
or while True
in any function then it stops "mainloop" and everything freeze.