Pygame Window Closing Automatically

Get code examples like 'how to make a ping pong game in python' instantly right from your google search results with the Grepper Chrome Extension.

im doing this :
http://www.learningpython.com/2006/0...game-part-one/
and when closing the program the window stays up and doesnt respond. i
tried adding this:
http://www.pygame.org/wiki/FrequentlyAskedQuestions
bu it doesnt work, or maybe im doing it wrong.
heres the code without the added tutorial exit:
import os, sys
import pygame
from pygame.locals import *
if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'
class PyManMain:
''The Main PyMan Class - This class handles the main
initialization and creating of the Game.''
def __init__(self, width=640,height=480):
''Initialize''
''Initialize PyGame''
pygame.init()
''Set the window Size''
self.width = width
self.height = height
''Create the Screen''
self.screen = pygame.display.set_mode((self.width
, self.height))
def MainLoop(self):
''This is the Main Loop of the Game''
while 1:
for event in pygame.event.get():
if event.type pygame.QUIT:
sys.exit()
class Snake(pygame.sprite.Sprite):
''This is our snake that will move around the screen''
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('snake.png',-1)
self.pellets = 0
if __name__ '__main__':
MainWindow = PyManMain()
MainWindow.MainLoop()
  • I'm new to programming, python and pygame. This is some code I wrote to draw random colored rectangles on an 800 x 600 canvas. It does what I expected it to do but becomes unresponsive if I click anywhere on the window. I am on a 64 bit windows 7 system running 32 bit python 2.7 with the appropriate pygame 1.9.1.
  • Dec 30, 2018 Everything runs smoothly until I click the red X. When I click it, the window doesn't close and all that happens is that the colourful red beach ball thing shows up whenever I hover my mouse over the Pygame window and the window just does not respond. It seems like the pygame.quit or pygame.display.quit functions do not work for some reason.
Pygame Window Closing Automatically

Hello people, this is going to be our first tutorial in which we will learn how to create our first game window in Pygame and Python.

So, the first step is to open VS Code and create a python file inside your directory.

1. Click on Create File:

Pygame

2. Name your file with .py extension in the end

3. Now write ‘import pygame’ and run it.

Pygame window closing automatically update

If you see ‘ pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html‘ Then you are on right track, else there might be some problem with your installation. Check out our previous article on Getting Started with Pygame.

Now let’s learn!

Importing the library:

To import pygame to our python file, we use the ‘import’ keyword and then the name of the package/library.

Initializing Pygame:

So, in order to access all the methods and functions of pygame, we need to initialize it first.

Pygame

To initialize Pygame, we need to write the following code.

This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do. You can also easily initialize each pygame module by hand.

Creating windows screen:

If you run the above code, it won’t do anything except displaying a hello message from Pygame Community. To create our game, we need a surface to put our game objects. So that’s why we create a window or screen. By Window/Screen I mean that it is the surface where we will put our game objects and run our game.

So, to create our screen we require the display module from pygame, because display module controls the display window and screen. And inside display module, we need to access the set_mode() function to initialize the window or screen for display.

set_mode() takes 5 arguments. And below is it’s Syntax:

Pygame Window Closing Automatically Reset

set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0)

This function will create a display Surface. The arguments passed in are requests for a display type. The actual created display will be the best possible match supported by the system.

The size argument is a tuple of a pair of numbers representing the width and height. The flags argument is a collection of additional options. The depth argument represents the number of bits to use for colour.

The Surface that gets returned can be drawn to like a regular Surface but changes will eventually be seen on the monitor. We can simply create the window and show it but we need to customize it in the further. So, we will store it in a variable for our ease.

To create the screen, we need to write the following code:

Pygame Window Closing Automatically Download

But now if you run it. The screen will just appear for an instant and then disappear. Well that is because there is nothing else in the program that will keep it running so after it displays the screen, there is nothing else to execute so it terminates and so does the screen.

To keep the screen remain on our monitor, We will run a while loop after the above code. But don’t run it instantly after adding while loop that is given below, because there is nothing there in the program that will stop the while loop, so your screen would look like that it is hanged and nothing will work on it, not even the close button, in that case, you may need your task manager to kill it. So to prevent that, we use events. We will learn more about them in the future articles but for now, you need to know that events in pygame are the activities that are happening on the screen/window like clicking, moving the cursor, keypress, etc.

So after adding the while loop, your program must be looking like this:

Instead, we add an if statement that will check all the events that are happening on our screen and if the close button is clicked, then it returns False that will break the loop and terminate the program.

So we will also create a boolean variable that takes True or False to check if the program is running or not. Example: If isRunning True; then keep looping else if isRunning False; that will break the while-loop.

So, consider the following snippet of code and try to understand it.

Explanation of the above code:

isRunning is a boolean variable that takes only True and False. And in the while-loop, before entering inside it we have added a statement isRunning True. It checks if the value of isRunning is True or not, if it is then loop through else break the loop and move out of it.

Pygame Window Keeps Closing

Inside the while-loop we have a for-loop that iterates through the events that are happening inside the game window with the help of the statement pygame.event.get() and stores it inside a variable called event. And then inside the for-loop, we have an if statement that checks if the type of event that happened on the screen was a Quit type of event. (QUIT type events occur when the user clicks on the close button). And if the type of event that happened and pygame.QUIT event are equal then set isRunning = False, that will break the while-loop after the execution that is required further in the loop is completed, else it keeps game screen/window running.

Your final code window after running the program must be looking like this:

So, now you know how to create a display screen/window for your game in python using the pygame library. Now we will learn how to customize our display screen/window in the next article.

Thanks for reading

Keep learning

If you found something wrong in this article, please let us know

Pygame Quit

Also Read: