Search code examples
pythonpython-3.xtkinterpygamecx-freeze

How to compile executable with cx_Freeze with modules in Python 3.x


This is my first post here, so if I make a mistake please tell me, I'll correct it. I am in python 3.6, windows 10, I have a program that I need to compile with cx_Freeze. I cannot get my setup.py to work, it has an error when I try to compile. The program I am trying to compile starts with:

import pygame
from pygame.locals import *
import sys
import time
import tkinter
from tkinter import filedialog
from tkinter import messagebox

I need all of these to make the program work, yet I need to compile it with cx_Freeze, Somebody please help me!

My setup.py is

from cx_Freeze import setup, Executable

base = None

executables = [Executable("to-compile.py", base=base)]

packages = ["idna","os","sys","tkinter","pygame"]
options = {'build_exe' : {'packages':packages}}

setup(name="<any name>",options=options,version="<any number>",description="<any description>",executables=executables)

I have a compiler.bat that contains:

python setup.py build

And my error is: Powershell Error

Seems like I cannot insert images yet I need a reputation.

PyInstaller does not work:

I will post error code on pastebin

If there is a solution to the problem with py2exe(or whatever variation of that compiler), please tell me just keep in mind that I am in python 3.


Solution

  • You need to set the environment variables TCL_DIRECTORY and TK_DIRECTORY and to tell cx_Freeze to include the Tcl and Tk DLLs using the build_exe option include_files as done in this answer. If you are using cx_Freeze 5.1.1 or 5.1.0, you need to do it slightly differently, see this answer.

    Furthermore, you should set base = "Win32GUI" for GUI applications under Windows.

    In summary, assuming you are using cx_Freeze 5.1.1 (the current version), try to use the following setup script:

    from cx_Freeze import setup, Executable
    
    import os
    import sys
    PYTHON_INSTALL_DIR = os.path.dirname(sys.executable)
    os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
    os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')
    
    include_files = [(os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join('lib', 'tk86t.dll')),
                     (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), os.path.join('lib', 'tcl86t.dll'))]
    packages = ["idna","os","sys","tkinter","pygame"]
    options = {'build_exe' : {'packages':packages, 'include_files':include_files}}
    
    # GUI applications require a different base on Windows (the default is for a console application).
    base = None
    if sys.platform == "win32":
        base = "Win32GUI"
    
    executables = [Executable("to-compile.py", base=base)]
    
    setup(name="<any name>",options=options,version="0.1",description="<any description>",executables=executables)