import turtle
= turtle.Screen()
screen = turtle.Turtle()
pen
pen.penup()
def got_click(x, y):
pen.goto(x, y)
pen.write(f"Got click at {x}, {y}",
=("Arial", 12, "normal"))
font
screen.onclick(got_click) screen.mainloop()
Event handling
Example: turtle graphics
- What is the object
Screen
? - What is the function
onclick()
doing? What is its argument? (Check the documentation) - See also the functions
ondrag()
(here),onkey()
(here), etc
Some ideas - try to make it:
- draw a person where you click
- count how many times you clicked
- say how long it’s been since the last click (use time.time())
- switch it from screen.onclick to pen.onclick and have it go to a random location
- keep track of the fastest click so far
- have it record 10 clicks and show the average time it took
- have the turtle walk by using WASD keys
Example: PyGame
import pygame
pygame.init()
# Creating window
= pygame.display.set_mode((800, 300))
gameWindow "Event Handling")
pygame.display.set_caption(
= False
exit_game = False
game_over
# Creating a game loop
while not exit_game:
for event in pygame.event.get(): # For Loop
if event.type == pygame.QUIT:
= True
exit_game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
print("You have pressed right arrow key")
elif event.key == pygame.K_LEFT:
print("You have pressed left arrow key")
pygame.quit() quit()
Definitions
- Event handling is programming paradigm or pattern that involves capturing and responding to events that occur in a program. It typically has the following components:
- Event Source: The entity that generates or emits events. This could be a user action (like clicking a button or pressing a key) or some other system-generated event.
- Event Object: An object that represents the event and contains information about it, such as the type of event, the target element (if applicable), and any additional data.
- Event Listener (or Handler): A function or method that is registered to receive and respond to specific types of events. When an event occurs, the corresponding listener is invoked.
- Event Loop (or Dispatcher): The mechanism that manages the flow of events and dispatches them to the appropriate listeners. The event loop waits for events to occur and then triggers the corresponding listeners.
- Propagation: The process by which events are propagated or passed through the event hierarchy. For example, an event may be handled by the target element first and then propagated to its parent/child classes.
- Event handling is commonly used in graphical user interfaces (GUIs) to respond to user interactions, but it can also be used in other types of applications to handle a wide range of events, such as network events, file system events, and timer events.
For the previous example (PyGame), ANSWER:
- What are the event objects?
- Where is the event loop?
- Where are the event handlers?
- Try to add an event that will trigger the variable
exit_game
toTrue
. See PyGame events in this webpage.