When I run: pyinstaller game.py
it works fine. I copy and paste my resources folder into dist and the game runs perfectly.
However, there's so many other files in the dist folder that it would be confusing for people to find the file to click on, so I wanted to use --onefile
.
I tried to do so and pasted the resource folder into dist and tried running the game, the console window appeared for a second then disappeared almost immediately. (I'm assuming there's an dependency I'm missing, but how can that be? it works fine without --onefile
)
Does --onefile not work with my layout for importing images and fonts or something?
Images:
if getattr(sys, 'frozen', False):
CURRENT_DIRECTORY = sys._MEIPASS
else:
CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
bg = (pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl0.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl1.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl2.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl3.png")))
Fonts:
font = pygame.font.Font(os.path.join(CURRENT_DIRECTORY, r"Resources\arial.ttf"), 36)
Well, it took ages but I believe I now have the answer to my question for anyone interested.
When running my game in my IDE, it would work fine and I would import relevant pictures like this:
bg = (pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl0.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl1.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl2.png")),
pygame.image.load(os.path.join(CURRENT_DIRECTORY, r"Resources\backgroundlvl3.png")))
For some reason, if I moved my resources folder and the game.py, to another directory, when i ran the game, I would get a nameError: name 'os' is not defined python. This is a mystery to me however, I also noticed that pyinstaller does not like this format of importing images and therefore, would not work for --onefile.
Therefore, I tried this alternative:
bg = (pygame.image.load(os.path.join('Resources', 'backgroundlvl0.png')),pygame.image.load(os.path.join('Resources', 'backgroundlvl1.png')),pygame.image.load(os.path.join('Resources', 'backgroundlvl2.png')),pygame.image.load(os.path.join('Resources', 'backgroundlvl3.png')) )
This for some strange reason, works in my IDE, however, when I right click the .py file and press open with -> python 3.8, it crashes. Regardless, it seemed to work for pyinstaller.
What to take away:
If you are using pyinstaller and you want one single file, use pyinstaller --onefile name.py
. Ensure that the folder you use which has your dependencies is referred to in your name.py with os.path.join('foldername', 'file')
. I had to do this specifically: pygame.image.load(os.path.join(....