一次彻底搞定python打包exe

示例程序目录结构

│—— demo.py
|—— res
  |—— fugu.png
  |—— sushiplate.jpg 

实例程序demo.py

import pygame
from pygame.locals import *
from sys import exit
import os,sys

if getattr(sys, 'frozen', False):
    # 打包后获取路径
    cur_path = sys._MEIPASS
else:
    # 没有打包后获取路径
    cur_path = os.path.dirname(__file__)

background_image=os.path.join(cur_path,'res/sushiplate.jpg')
mouse_image=os.path.join(cur_path,'res/fugu.png')

pygame.init()

screen=pygame.display.set_mode((640,480),0,32)
pygame.display.set_caption('Hello pygame')

backgroud=pygame.image.load(background_image).convert()
mouse_cursor=pygame.image.load(mouse_image).convert_alpha()

while True:
    for event in pygame.event.get():
        if event.type== pygame.QUIT:
            exit()

    screen.blit(backgroud,(0,0))

    x,y=pygame.mouse.get_pos()
    x-=mouse_cursor.get_width()/2
    y-=mouse_cursor.get_height()/2
    screen.blit(mouse_cursor,(x,y))

    pygame.display.update()

资源适配打包的相关代码

if getattr(sys, 'frozen', False):
    # 打包后获取路径
    cur_path = sys._MEIPASS
else:
    # 没有打包后获取路径
    cur_path = os.path.dirname(__file__)

background_image=os.path.join(cur_path,'res/sushiplate.jpg')
mouse_image=os.path.join(cur_path,'res/fugu.png')

一键打包命令(将资源文件一同打包)

pyinstaller -F -w --add-data "res/;res/"  demo.py

你可能感兴趣的:(一次彻底搞定python打包exe)