用pip直接安裝pygame失敗,
pip install pygame
原因無非是連接外網的下載速度太慢,導致安裝失敗。可以另闢蹊徑,使用國內鏡像下載:
windows 7下,直接在user目錄中新建一個pip文件夾
例如,我的是C:\Users\Administrator\pip ,
新建一個文件名爲 pip.ini,保存內容如下:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
現在再安裝pygame,升級pip只需要幾秒鐘的時間
臨時使用:
可以在使用pip的時候加參數-i https://pypi.tuna.tsinghua.edu.cn/simple
例如:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider
這樣就會從清華這邊的鏡像去安裝pyspider庫。
這時,在cmd中驗證一下是否安裝成功:
在Sublime Text中輸入一下代碼,按ctrl+B運行
import pygame, sys
from pygame.locals import *
white = 255,255,255
black = 0,0,0
pygame.init()
screen = pygame.display.set_mode((600, 500))
myfront = pygame.font.Font(None,60)
textImage = myfront.render("Hello Pygame", True, black)
while True:
for event in pygame.event.get():
if event.type in (QUIT, KEYDOWN):
sys.exit()
screen.fill(white)
screen.blit(textImage, (100, 100))
pygame.display.update()
得到結果:
但是,在pycharm中運行此代碼還是會報錯
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/python/greedysnake/snake.py", line 1, in <module>
import pygame
ModuleNotFoundError: No module named 'pygame'
許多文章會介紹從File→Settings→Project Interpreter,點右上的加號,搜索pygame,然後點擊Install Package,安裝pygame,但我的還是會安裝失敗:
現在我們可以用以下三種方法之一在項目中成功導入pygame:
方法一:
依次點擊File→Settings→Project Interpreter,
點擊右上角的小齒輪
再點擊右上角的+號
根據自己的python安裝目錄,選擇自己的解釋器。至此,pygame包就出現在列表裏。
方法二(一個簡單粗暴的方法):
1. 複製python安裝目錄下\Lib\site-packages中的pygame和pygame-1.9.6.dist-info兩個文件夾,到pycharm項目下的\venv\Lib\site-packages中,
如圖:
這時可以發現File→Settings→Project Interpreter中已經有pygame包了
方法三(推薦的方法):
在新建項目時,點擊File→New Project
現在可以查看:
相信現在你知道爲什麼會出現項目中沒有pygame這個情況了