简体   繁体   English

无法在 PyCharm 中导入 pygame

[英]Can't import pygame in PyCharm

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.每当我在 PyCharm 中键入import pygame时,它都会说该模块未安装,但我可以在 python 模式下将其导入终端。

In your py script:在您的 py 脚本中:

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.我建议将 pygame 的路径添加到要从中执行脚本的pygamePYTHONPATH环境变量中。 rather than editing the sys.path in py script directly.而不是直接在 py 脚本中编辑sys.path

PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. PYTHONPATH是一个环境变量,您可以设置它以添加其他目录,python 将在其中查找模块和包。 eg:例如:

If you are in windows you can use the set command to extend PYTHONPATH .如果您在windows中,则可以使用set命令扩展PYTHONPATH

in linux:在 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.虚拟环境的主要目的是管理特定项目的设置和依赖关系,而不考虑其他 Python 项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM