Pygame not loading png after making .exe with Pyinstaller

前端 未结 2 1662
小蘑菇
小蘑菇 2020-12-24 03:50

I\'ve been trying to make an .exe from my .py game and it\'s been really frustrating.

I\'m using Python 3.5.2, Pygame 1.9.2 and Pyinstaller 3.2.

The game is

2条回答
  •  生来不讨喜
    2020-12-24 04:42

    When you compile with PyInstaller, all the files are moved to a different directory when you run your exe. So, to get to this location, add this to the beginning of your code, before you generate paths

    import sys
    
    if getattr(sys, 'frozen', False): # PyInstaller adds this attribute
        # Running in a bundle
        CurrentPath = sys._MEIPASS
    else:
        # Running in normal Python environment
        CurrentPath = os.path.dirname(__file__)
    

    All your folder paths can then be generated from your location

    spriteFolderPath = path.join(CurrentPath, 'sprites') # Do the same for all your other files
    

    Then, when you've got the location you're executing in, you can get all your files from there :

    title_screen = pygame.image.load(path.join(spriteFolderPath, 'title_screen.png')) # Use spriteFolderPath instead of img_dir
    

    I also see that you've got other fonts/stuff, you can do the same to load them

    fontRobotoLight = pygame.font.Font(path.join(CurrentPath, 'Roboto-Light.ttf'))
    

    For your icon, just paste a temporary icon.ico in your main folder and type pyinstaller -i "icon.ico" "spec_file.spec"

    Finally, as I've had the same problem before, I recommend you compile your exe simply by running pyinstaller "spec_file.spec"

提交回复
热议问题