2
\$\begingroup\$

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.

    import pygame as pg
    from random import randint as rand

    pg.init()
    screen_size = (800,600)
    canvas = pg.display.set_mode(screen_size)
    pg.display.set_caption('Random Rects')
    curEvent = pg.event.poll()
    running = True
    todraw = []

    class rect:
        def __init__(self, x, y, (width, height)):
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.color = (rand(0,255),rand(0,255),rand(0,255))
        def topygame(self):
            return self.color,(self.x,self.y,self.x+self.width,self.y+self.height)

    for x in range(100):
        todraw.append(rect(rand(0,800), rand(0,600), (rand(0,100), rand(0,100))))

    for x in todraw:
        pg.draw.rect(canvas, *(x.topygame()))

    while running:
        pg.display.flip()
        for event in pg.event.get():
            if event.type==pg.event.QUIT:
                running = False
\$\endgroup\$

3 Answers 3

4
\$\begingroup\$
Traceback (most recent call last):
  File "C:\Users\Kylotan\Desktop\test_pg.py", line 31, in <module>
    if event.type==pg.event.QUIT:
AttributeError: 'module' object has no attribute 'QUIT'

I added from pygame.locals import * to the top and changed it to just 'QUIT', and it works for me.

It's not the clicking that makes the window unresponsive, it's that the clicking makes the operating system try to send it an event, which it realises never gets handled, so the OS realises something is wrong. The reason it never gets handled is probably because the Pygame app had already crashed (with the error above) but for some reason hadn't closed the rendering window yet.

\$\endgroup\$
1
  • \$\begingroup\$ Right you are. I would click the up arrow, but I need 15 reputation first it seems. In any case thank you very much. \$\endgroup\$
    – Ceryn
    May 11, 2012 at 13:41
0
\$\begingroup\$

Add

pygame.event.wait()

to your main loop - without this your application will render data too fast and it will cause application "hang"

\$\endgroup\$
0
\$\begingroup\$

When you click inside the window and you are not defining any state condition when the event happens it may hang.

So add this condition anywhere:

for event in pygame.event.get():
    if event.type == MOUSEBUTTONUP:
        None 

This would tell it when you click the mouse do nothing so it will not hang.

That worked for me.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .