Python Forum
[PyGame] Why did they put a while loop here?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Why did they put a while loop here?
#1
I know nothing about pygame, just started learning about it. I got the code below from here.

I just put it in a function for trying it out in the Idle shell.

This draws a rectangle OK, but isn't the while loop always working??

Wouldn't it be enough to just draw the rectangle?

def rect():
    import pygame 
    pygame.init() 
    scr = pygame.display.set_mode((500,500)) 
    color = (0,0,255)
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        pygame.draw.rect(scr, color, pygame.Rect(60, 60, 100, 100)) 
        pygame.display.flip() 
    pygame.quit()
Reply
#2
The loop is needed to get user input and to update the display.
The loop will exit if the following statement is true
if event.type == pygame.QUIT:
    running = False
https://pygame.readthedocs.io/en/latest/...event-loop Wrote:Show the event loop
The most essential part of any interactive application is the event loop. Reacting to events allows the user to interact with the application. Events are the things that can happen in a program, such as a
  • mouse click,
  • mouse movement,
  • keyboard press,
  • joystick action.
The following is an infinite loop which prints all events to the console:

while True:
    for event in pygame.event.get():
        print(event)

https://pygame.readthedocs.io/en/latest/...p-properly Wrote:Quit the event loop properly
In order to quit the application properly, from within the application, by using the window close button (QUIT event), we modify the event loop. First we introduce the boolean variable running and set it to True. Within the event loop we check for the QUIT event. If it occurs, we set running to False:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()
Once the event loop, we call the pygame.quit() function to end the application correctly.
Pedroski55 likes this post
Reply
#3
Thanks, I have bookmarked the pygame docs page.

Now I know where to look!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020