Search code examples
pythonfilepygamepycharmexe

pygame project works in IDE, after I converted it to .exe and run it, the game window opens for half a second before closing


Again, this works perfectly fine in PyCharm. I wrote the script in PyCharm by following a Space Invaders Game toturial, and in the code it calls on some files like "ufo.png". I need some help on getting the .exe of my code to run like it does in the IDE. I used pyinstaller to convert the main.py into an exe and it showed up in the C:\Users\MyName\PycharmProjects\pygame\dist folder as main.exe

When I tried to run the exe (by double clicking on main.exe) command prompt would open for 2 seconds or so, the game window would open up very shortly and it was titled "space invaders" just like it is titled in the IDE.

The only exception is that it immediately closes without displaying anything. Both the game window and the command prompt close right away. When I run the code by calling it in command prompt under the right CD, it tells me the error responsible:

C:\Users\MyName\PycharmProjects\pygame\dist>main.exe
pygame 2.0.2 (SDL 2.0.16, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "main.py", line 73, in <module>
    font = pygame.font.Font("freesansbold.ttf", 32)
TypeError: expected str, bytes or os.PathLike object, not BytesIO
[1840] Failed to execute script 'main' due to unhandled exception!

I moved all the files from the IDE (here are the IDE files used in my program) my files from PyCharm goes here

So I copied those files and moved them into the same folder as the main.exe thinking that there was some issue with calling on the files.

here's how the file with main.exe as well as some .png and .wav files used in the program looks like

Do I need to include the png's and stuff somewhere else, or do i need to change some of my code?? Here is the bit that command prompt is getting tripped up on.

font = pygame.font.Font("freesansbold.ttf", 32)

I don't know what I can do to fix it, I've been looking for an answer for hours. If anyone could help it will be greatly appreciated.


Solution

  • I figured it out. The problem was the font. freesansbold.ttf did not exist in the directory.

    What I did:

    1. I went to C:\Windows\Fonts
    2. I copied out arial.ttf
    3. Went to where my code was stored and added it to the same folder.

    Looked like this: my code location

    After, I repackaged the main.py to main.exe, removed it from the dist file and placed it with the rest of the code like you see in the picture above, the program was able to access that font and the code executed correctly.