使用cx_freeze和pyGame创建“独立”包

1 投票
1 回答
1883 浏览
提问于 2025-04-18 14:22

网上有人提到:“用Python来打包你的程序,让大家都能下载和玩,真的是一件麻烦事,这也是我不想用Python的原因。我在网上找了很多解决办法,但都不太满意。”

我也同意这个观点。到现在为止,我还没能把用pyGame写的Python代码“编译”(其实更准确的说法是打包)成一个可以在Ubuntu上运行的exe文件。最后一步就是希望能让Windows和Mac OS也能运行。

我使用的是:
Python 2.7.6
[GCC 4.8.2] 在 linux2 上
描述:Ubuntu 14.04 LTS
版本:14.04
代号:trusty

用cx_freeze来“编译”的示例游戏代码:

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((1000, 1000), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
catx = 275
caty = 150
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    fpsClock.tick(FPS)

1 个回答

1

要编译Python程序,你需要创建一个新的脚本,叫做setup。

代码如下:

from cx_Freeze import setup, Executable, re

build_exe_options = {"include_files" : ["cat.png"]}

setup(name = "name of program",
      version = "0.1",
      description = "",
      options = { "build_exe" : build_exe_options },
      executables = [Executable("name of program.py")]) # Program name

把这段代码放到Python文件夹里,路径是C:\python\27,然后把你的程序也放进去。接下来,打开命令提示符,输入cd C:\python27,然后再输入C:\python27\python.exe setup.py build,这样可执行文件就会出现在Python文件夹里的build文件夹里。

撰写回答