Skip to content
Advertisement

Pygame: How to display a new box when user clicks an area, and close the box when the user clicks again

I am new to python and pygame and I am developing a weather app as a project to learn both.

I want to display a new rectangle when a user is clicking an area (=button) of the screen. The new rectangle should be visible until the user clicks again, this time anywhere on the screen.

I have my main loop where the screen is drawn, and then checking for event MOUSEBUTTONUP and with collidepoint checking if the mouse was on the button and then updating variable newscreen to True

Then I have a new loop that should be running until the user is clicking again, anywhere on the screen. The problem is that the new while loop is breaking as soon as the mouse is moved. It also looks like the first condition, checking if the user is clicking the button, is returning true in every iteration until the mouse is moved. Why is this not only returning true one time?

Can this be done without having a second while loop?

JavaScript

Advertisement

Answer

You have to draw the rectangles depending on the state of newscreen:

JavaScript

All the events need to be handled in one event loop. Toggle the state of newscreen when the button is clicked (newscreen = not newscreen):

JavaScript

Complete example:

JavaScript

The typical PyGame application loop has to:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement