It "crashes" because you don't handle the events. See PyGame unresponsive display or PyGame window not responding after a few seconds.
You have to handle the events in the application loop. See pygame.event.get()
respectively pygame.event.pump()
:
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
If you want to wait for the mouse to be clicked, you have to handle the events in the loop.
Anyway, if you only want to toggle once after clicking the mouse button, you'll need to use the mouse events. The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event
.
For instance:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if button.collidepoint(event.pos) and event.button == 1:
toggle()
See also Pygame mouse clicking detection