Can't import pygame in PyCharm

Viewed 161

Whenever I type import pygame in PyCharm it says the module isn't installed, but I can import it in the terminal in python mode.

2 Answers

In your py script:

import sys
##lets check if this module appears in the sys.path

exist = False
for path in sys.path:
    if 'pygame' in path:
        print path
        exist = True
if not exist:
    sys.path.append('... the path to the pygame dir.. where the __init__.py')

I recommend do add the path of pygame to the PYTHONPATH environement variable of the shell you want to execute your script from. rather than editing the sys.path in py script directly.

PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

If you are in windows you can use the set command to extend PYTHONPATH.

in linux:

# make python look in the pygameDirPath subdirectory of your home directory for
# modules and packages 
export PYTHONPATH=${PYTHONPATH}:${HOME}/pygameDirPath

This also happens when you don't configure your virtual environment correctly.

Make sure that you select the check box Inherit Global Site Packages when you are creating the project.

Inherit Global Site Packages

The main purpose of virtual environments is to manage settings and dependencies of a particular project regardless of other Python projects.

Related