6

I'm fairly new to programming in general and I just started using python to try and make a simple game using pygame. If I run the following code in the Python IDLE shell it works fine but if I use Pyscripter I get the error:

SyntaxError: import * only allowed at module level

I really like using Pyscripter because so far it has made learning the syntax much easier but now I don't understand what is wrong. Any help would be great. Thanks.

import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400,300),0,32)
pygame.display.set_caption('Hello World!')
while True: #main game loop
     for event in pygame.event.get():
         if event.type == QUIT:
            pygame.quit()
            sys.exit()
     pygame.display.update()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3189015
  • 63
  • 1
  • 6
  • 6
    Hrm, I wasn't aware that Pyscripter runs your code in a function. The exception is raised because inside a function you are not allowed to create a variable number of locals (which is what `from modulename import *` does). – Martijn Pieters Jan 13 '14 at 17:42
  • You can 'fix' it by only importing names you are actually using; `from pygame.locals import QUIT` would do here. – Martijn Pieters Jan 13 '14 at 17:45
  • This is weird. Executing things inside a function instead of at the global level significantly changes the semantics of the code. The fact that `import *` isn't working is just one of the symptoms. – Sven Marnach Jan 13 '14 at 17:56
  • Thanks, that worked. Would you recommend not using Pyscripter then? Seems like it will get annoying if I have to individual import everything. – user3189015 Jan 13 '14 at 18:45
  • which version of pyscripter are you using? Are you sure your import code is not inside the autogenerated main function? – Bartlomiej Lewandowski Jan 13 '14 at 19:48
  • 1
    O wow, Bartlomiej is right. What a silly mistake. Thank you so much. – user3189015 Jan 13 '14 at 19:50

1 Answers1

-1

The problem is when you execute from pygame.locals import * you are accessing all from a file, not a module. When you do something like from pygame import *, it should work. It is just that you can only use import * at the module level

Krishnan Shankar
  • 780
  • 9
  • 29
  • 2
    This seems entirely wrong, as `pygame.locals` is a module, it's a submodule of the `pygame` package. The issue isn't where the import is coming *from*, but where it's being imported *to*. – Blckknght Apr 28 '20 at 21:12