使用Macports安装pygame

时间:2014-09-12 14:52:11

标签: python pygame sublimetext2

我正在通过macports安装pygame。我跟着instructions这样,

sudo port install py26-game

写了这样的pygame代码:

#image settings
bif = "bg.jpg"
mif = "ball.jpg"

#Basic Settings for pygame
import pygame, sys
from pygame.locals import *

pygame.init()

#Create a screen and load the images
screen = pygame.display.set_mode((640,360),0,32) #size,flag,bit

background = pygame.image.load(bif).convert()
mouse_c = pygame.image.load(mif).convert_alpha()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    screen.blit(background,(0,0))

    x,y = pygame.mouse.get_pos()
    x -= mouse_c.get_width()/2
    y -= mouse_c.get_height()/2

    screen.blit(mouse_c,(x,y))

    pygame.display.update()

我使用sublime text 2来构建游戏,但我有这个错误:

Traceback (most recent call last):
  File "PygameTutorial.py", line 6, in <module>
    import pygame, sys
ImportError: No module named pygame

在我的终端中,尝试了同样的错误:

>>> import pygame
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pygame

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要确保使用的是MacPorts版本的Python,而不是内置版本。假设您的MacPorts安装位于/opt/local,您需要执行以下操作:

  1. 修改您的~/.profile并将此行包含在最底部:

    export PATH=/opt/local/bin:$PATH
    

    重新启动终端会话,在命令行上运行python,看看是否可以导入pygame。

  2. 如果可行,请使用JSON语法在Sublime中打开一个新文件并粘贴以下内容:

    {
        "cmd": ["/opt/local/bin/python", "-u", "$file"],
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    

    选择 Packages/User ,将文件保存在Python2.sublime-build目录Packages,其中Sublime Text 2 -> Preferences -> Browse Packages...是打开的文件夹 - 它应该是{{} 1}}。然后,当您想要构建Python项目时,选择 ~/Library/Application Support/Sublime Text 2/Packages 并点击 B 进行构建。

    或者,如果您要使用 Tools -> Build System -> Python2 设置,则可以编辑原始Tools -> Build System -> Automatic文件。如上所示打开Python.sublime-build文件夹,转到Packages目录,然后在Sublime中打开Python。将内容更改为上述内容(基本上只需将Python.sublime-build更改为"cmd": ["python", ...并保存。请注意,这仅适用于Sublime Text 2;如果您使用ST3,则需要安装PackageResourceViewer以从压缩的"cmd": ["/opt/local/bin/python", ...文件中提取Python.sublime-build文件。

答案 1 :(得分:0)

检查目录中的“site-packages”文件夹中是否有pygame:

Python27/lib/site-packages

如果您找到py26-game

之类的内容,有时包含它的文件名与“pygame”不同

尝试将导入更改为该名称。