import * only allowed at module level. Python 3.3 using Pyscripter
Asked Answered
S

1

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()
Shulamith answered 13/1, 2014 at 17:38 Comment(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).Ballon
You can 'fix' it by only importing names you are actually using; from pygame.locals import QUIT would do here.Ballon
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.Leuco
Thanks, that worked. Would you recommend not using Pyscripter then? Seems like it will get annoying if I have to individual import everything.Shulamith
which version of pyscripter are you using? Are you sure your import code is not inside the autogenerated main function?Renatorenaud
O wow, Bartlomiej is right. What a silly mistake. Thank you so much.Shulamith
S
-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

Squier answered 28/4, 2020 at 19:55 Comment(1)
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.Paleogeography

© 2022 - 2024 — McMap. All rights reserved.