KeyError: 'TCL_LIBRARY' when building using cx_freeze - python-3.x

When trying to build my file using cx_freeze it spits out an error
raise KeyError(key) from None
KeyError: 'TCL_LIBRARY'
I know there are other posts describing this, but I already tried adding
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll')
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll')
which is what other posts recommend, but i still get the same error
This is my code so far
from cx_Freeze import setup, Executable
import sys, os
shortcut_table = [
("DesktopShortcut", # Shortcut
"DesktopFolder", # Directory_
"program", # Name
"TARGETDIR", # Component_
"[TARGETDIR]main.exe",# Target
None, # Arguments
None, # Description
None, # Hotkey
"icon.ico", # Icon
None, # IconIndex
None, # ShowCmd
'TARGETDIR' # WkDir
)
]
base = None
if sys.platform == "win32": base = "Win32GUI"
os.environ['TCL_LIBRARY'] = "C:\\Program Files\\Python35-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Program Files\\Python35-32\\tcl\\tk8.6"
msi_data = {"Shortcut": shortcut_table}
bdist_msi_options = {'data': msi_data}
executables = [Executable("main.py", shortcutName='2048', shortcutDir='DesktopFolder', icon='icon.ico', base=base), Executable("extras.pyw"),]
setup(
name = '2048',
author = 'Ethan',
options={
"build_exe": {
"packages":["pygame", "sys", "random", "os", "ctypes"],
"include_files":["scores.txt",
"icon.ico",
]
}},
executables = executables,
version = "1.0"
)
edit: changes to code
after changing the code, it currently runs without error but only creates a folder with an ul-launchable exe
build
exe.win-amd64-3.6
api-ms-win-crt-conio-l1-1-0.dll
api-ms-win-crt-convert-l1-1-0.dll
api-ms-win-crt-environment-l1-1-0.dll
api-ms-win-crt-filesystem-l1-1-0.dll
api-ms-win-crt-heap-l1-1-0.dll
api-ms-win-crt-locale-l1-1-0.dll
api-ms-win-crt-math-l1-1-0.dll
api-ms-win-crt-process-l1-1-0.dll
api-ms-win-crt-runtime-l1-1-0.dll
api-ms-win-crt-stdio-l1-1-0.dll
api-ms-win-crt-string-l1-1-0.dll
api-ms-win-crt-time-l1-1-0.dll
main.exe
python36.dll
VCRUNTIME140.dll
EDIT 2:
so i did some more tinkering and found out the TCL error comes from including ctypes(not sure why). So i removed it and changed my python version to 3.6 and it built perfectly. But i would prefer to have ctypes included as i use it to disable application scaling.
is there another way to deal with screen scaling or a way to fix the TCL error?

cx_freeze does not work with python 3.7 so switching to 3.6 allowed it to work, then adding
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
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')
sets the directory in order to use ctypes

Related

Is there any way to know what error occured when running a frozen app - cx_Freeze

I just finished freezing my program with cx_Freeze. When I try to run it, it just stops without showing any error messages, so I want to know if is there any way to know what's wrong with my program or my freezing script:
import sys, os
from cx_Freeze import setup, Executable
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
sys.path.append('pandastable')
includes = ["pandastable"]
includefiles = [
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),'ClasseAgents.py','ClasseData.py','ClassePerformance.py','ClasseTime.py','ClasseTraitement.py','PredictionFlux.py','icone.ico','VCbase.db'
]
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os","numpy","matplotlib","pandas",
#"scipy","seaborn","IPython","statsmodels",
"pandastable"],
"excludes": ['seaborn','statsmodels'],
"namespace_packages": ['mpl_toolkits'],
"include_msvcr": True,
"includes": includes,
"include_files": includefiles}
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [Executable("Main.py", base=base,
#copyDependentFiles = True,
targetName='TaskManager.exe',
shortcutName="TakManaer",
shortcutDir="DesktopFolder",
icon="icone.ico")]
setup( name = "Task manager for BPO",
version = "1.0",
description = "task manager est un gestionnaire de traitement intelligent",
options = {"build_exe": build_exe_options},
executables = executables)
Try to redirect the output of your executable into a file with the following command in a cmd prompt:
TaskManager.exe > out.txt
The content of the output file can then be viewed e.g. with:
type out.txt
The output file might contain additional error messages for applications frozen with the Win32GUI base.

Packaging Python file with cx_Freeze

I am trying to package my Python code into an exe file but after following all the instructions on the link below, I managed to build the an exe file but when I try to run it, nothing happens.
https://cx-freeze.readthedocs.io/en/latest/distutils.html
My setup.py file is
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os","tkinter", "pandas" , "openpyxl", "datetime", "time"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "login",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [Executable("login.py", base=base)])
My login file runs without any error on Anaconda.
Can someone comment what may cause the problem?

Python suprocess not working after cx_freeze

this is my first question on stack-overflow!
I am currently writing a Python script (well, actually a few scripts) to manage book collections, that I would now like to freeze and distribute (this is my first 'big' project).
After looking at many options I decided to try with Cx_Freeze.
(I'm using Python 3.6 and Cx_Freeze 5.1.1).
In this project I often use 'subprocess' to move from a script to another.
In the interpreter it works just fine, if I let Cx_Freeze make the build folder using
python setup.py build
it works as well, but when I try to create a distributable file with
python setup.py bdist_msi
after installation it starts and works up to the first call for a subprocess, then nothing more.
Here is setup.py
from cx_Freeze import setup, Executable
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
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')
setup(
name = "Libro",
version = "1.0.0",
options = {"build_exe": {
'packages': ["tkinter", "subprocess", ],
'include_files': [os.path.join(PYTHON_INSTALL_DIR, 'DLLs','tk86t.dll'), \
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), \
'logo50x50.gif', 'check_1.txt', 'check_2.txt', 'start.py', \
'createdb.py', *and_a_few_more_files*],
'include_msvcr': True,
}},
executables = [Executable("Libro.py",base="Win32GUI")]
And this is the Libro.py script that becomes the executable.
#This script checks the documents check_1 and check_2 and then launches
# createdb.py or start.py
import subprocess
from tkinter import *
import tkinter.messagebox as box
root= Tk()
root.withdraw()
with open('check_1.txt', 'r') as check_1:
for line in check_1:
line = line.strip()
value_1 = int(line)
with open('check_2.txt', 'r') as check_2:
for line in check_2:
line = line.strip()
value_2 = int(line)
if value_1 == 0 and value_2 == 0:
box.showinfo('Libro 1.0', '''
Welcome to the installation of Libro.
I am now creating the database for your catalogue.
This may take a moment.''')
subprocess.call("createdb.py", shell=True)
else:
subprocess.call("start.py", shell=True)
root.mainloop()
It starts, it looks for check_1 and check_2, shows the tkinter showinfo window and then... that's it.
I would be very grateful for any suggestion!! Thanks :)
You would need to freeze all of your scripts, not just the top level one! (create multiple Executable() entries). And then call subprocess to run the frozen executables. If you don't do that you'll end up requiring Python to be installed on the target machine -- and then why freeze any of it! Of course, it might also be helpful to explain why you need to run your code in a subprocess instead of directly.
In the end it looks like it would be easier and more economic to treat my scripts as modules and then import them when needed.
I tried some simplified operations and they seem to work.
For example:
being main.py
from tkinter import *
from modules import from_file
root = Tk()
root.title('Trial window')
btn_1 = Button(root, text='Read from file', command=from_file)
btn_1.grid(row=1, column=1)
and being modules.py
from tkinter import *
def from_file():
ft = open('text.txt', 'r')
string = ''
for line in ft:
line = line.strip()
string = string+line
ft.close()
root2 = Tk()
result = Label(root2, text=string)
result.grid(row=1, column=1)
root2.mainloop()
the script reads and visualize the content of 'text.txt' in the new windows it opens also after being frozen with cx_freeze.
PS The setup.py I used is
from cx_Freeze import setup, Executable
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
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')
setup(
name = "Prova",
version = "1.0.0",
options = {"build_exe": {
'packages': ["tkinter"],
'include_files' : [os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), \
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), 'text.txt'],
'include_msvcr': True,
}},
executables = [Executable("main.py", base="Win32GUI")]
)

Cannot fix pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.')

I am trying to build an .exe file of my Python application. I have tried various ways to create a setup file from both Github and Stackoverflow and I keep getting this same error:
pywintypes.error: (2, 'BeginUpdateResource', 'The system cannot find the file specified.').
I am using Python 3.6.1, and cx_Freeze to build the application.
Here are the different setup files I have tried:
Attempt 1:
import os.path
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = r'C:\Users\RedCode\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\RedCode\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
executables = [Executable("myprogram.py", base="Win32GUI")]
options = {
'build_exe': {
'include_files': [
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
]
},
}
setup(
name="Standalone.exe",
options=options,
version="0.1",
description='Simple tkinter application',
executables=executables, requires=['cx_Freeze', 'cx_Freeze']
)
Attempt 2:
from cx_Freeze import setup, Executable
import sys
import os
productName = "My Program"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', r'C:\Users\RedCode\PycharmProjects\Standalone' + productName]
sys.argv += ['--install-script', 'myprogram.py']
os.environ['TCL_LIBRARY'] = r'C:\Users\RedCode\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\RedCode\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
exe = Executable(
script="myprogram.py",
base="Win32GUI",
targetName="Product.exe"
)
setup(
name="Standalone.exe",
version="1.0",
author="Me",
description="Copyright 2012",
executables=[exe],
scripts=[
'myprogram.py'
]
)
Attempt 3:
import sys
import os
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "includes": ["tkinter"]}
def s_SourceFile():
if (sys.argv[0] == ''):
return __file__
else:
return sys.argv[0]
os.environ['TCL_LIBRARY'] = r'C:\Users\stefano.demattia\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\stefano.demattia\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(name="Standalone",
version="0.1",
description="My GUI application!",
options={"build_exe": build_exe_options},
executables=[Executable("myprogram.py", base="Win32GUI", targetName="Standalone.exe")])
Attempt 4:
application_title = "Car Database"
main_python_file = "cardb.py"
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "myprogram.py",
version = "0.1",
description = "Simple embedded database application",
executables = [Executable("myprogram.py", base = base)])
I have also tried pyinstaller but it keeps giving me a tuple out of range error no matter what I do, and I tried bbfreeze which I can't even get to install. I have checked my files and everything is there, so I do not see how it can still tell me a specified file is not found.
What else can I do or how can I edit the above attempts so that the application actually builds properly? Is there even a way to determine which file is missing?
Remove the version, I got the same error, looked at the code and noticed it was referencing versioning in the source, so thought I'd try it, and it fixed it for me.
I know the poster probably no longer needs this, but posting it for others that come across this in the future since I didn't see the answer anywhere else.
cx_Freeze.setup(
name="SampleName",
options={"build_exe": {"packages": ["tkinter", "os"],
"include_files": ['tcl86t.dll', 'tk86t.dll', 'closenew.png', 'sujata.png', 'config.py', 'ui_attributes.py']}},
version="0.01", # Remove this line
description="Tkinter Application",
executables=executables
)
I have removed the version and it worked.
cx_Freeze.setup(
name="SampleName",
options={"build_exe": {"packages": ["tkinter", "os"],
"include_files": ['tcl86t.dll', 'tk86t.dll', 'closenew.png', 'sujata.png', 'config.py', 'ui_attributes.py']}},
description="Tkinter Application",
executables=executables
)

How does cxFreeze include internal project modules?

Update:
I suspect this is an error in cxFreeze as I understand this should
go automatically.
end update
Update:
I missed an error given by cxFreeze:
Missing modules:
? Test.MyClass imported from main__main__
end update
I'm not sure what the proper term is for modules within project unlike sys or PyQt, so I'm going with internal project modules.
I have some example code below where I recieve the error "ImportError: cannot import name MyClass." and I would love to know how to get cxFreeze to compile that 'Test.py' module.
Here's my main code:
Main.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
#from guiObjects.MainWindow import MainWindow
from Test import MyClass
if __name__ == "__main__":
# Initializing the main window
app = QApplication(sys.argv)
widget = QMainWindow()
#mainWindow = MainWindow(widget)
test = MyClass()
widget.show()
sys.exit(app.exec_())
Test.py
class MyClass(object):
def __init__(self):
pass
__init.py__
'''empty'''
Setup.py
import sys
from cx_Freeze import setup, Executable
path_platforms = ( "C:\Python33\Lib\site-packages\PyQt5\plugins\platforms\qwindows.dll", "platforms\qwindows.dll" )
includes = ["re","sip","atexit","PyQt5.QtCore","PyQt5.QtGui"]
includefiles = [path_platforms]
excludes = [
'_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
'Tkconstants', 'Tkinter'
]
packages = ["os"]
path = []
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
"includes": includes,
"include_files": includefiles,
"excludes": excludes,
"packages": packages,
"path": path
}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
exe = None
if sys.platform == "win32":
exe = Executable(
script="../Main.py",
initScript = None,
base="Win32GUI",
targetDir = r"dist",
targetName="Main.exe",
compress = True,
copyDependentFiles = True,
appendScriptToExe = False,
appendScriptToLibrary = False,
icon = None
)
setup(
name = "Main",
version = "0.1",
author = 'me',
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [exe]
)
This problem happens when you run setup.py in a subfolder of where Main.py is located.
I now placed my setup.py in the same folder as Main.py. and changed my .bat file to python ../setup.py build install.
This seems to be a bug in cx_Freeze as it works fine for Python 2.7, but not Python 3.3.
Your test.py is wrong, you can't leave functions empty, try
class MyClass(object):
def __init__(self):
pass
and in setup.py mabye add "Test" into "includes"
includes = ["re","sip","atexit","PyQt5.QtCore","PyQt5.QtGui", "Test"]

Resources