Python - pygame error when executing exe file Python - pygame error when executing exe file tkinter tkinter

Python - pygame error when executing exe file


You need double backslashes:

From:

song = path + '\music\\' + selected_song

To:

song = path + '\\music\\' + selected_song

Or:

song = f"{path}\\{music}\\{selected_song}"


As I mentioned it comment update pygame to version 2.0.0.dev6 or newer, and another possible issue is when making .exe pyinstaller puts it in the dist folder. So if you haven't moved it from that folder, paths are incorrect and the files couldn't be located, hence the error.


When python programs are packaged up with pyInstaller, CXFreeze, etc. The first part of the execution is unpacking everything into a temporary location. Then the executable may not be run from that same directory either.

So it's important that the python program itself determines the current working directory and finds where its resource files are. Images, sounds etc. will no longer be at "./music" or "./assets/images", it's probably something more like "/tmp/cxunpack.125423/assets/sounds/".

The script needs to work out the location it is running from:

import sysimport os.pathif getattr(sys, 'frozen', False):  # Is it CXFreeze frozen    EXE_LOCATION = os.path.dirname( sys.executable ) else:    EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) 

And then use this in combination with os.path.join() to determine the correct path to the needed file:

song_filename = os.path.join( EXE_LOCATION, "music", "first.mp3" )pygame.mixer.music.load( song_filename )

Using os.path.join() is important because it makes your program more platform independent, and handles a few little problems with joining paths automatically.