I wrote the folowwing at the top of my script:
try:
from Tkinter import *
from Tkinter import messagebox
except ModuleNotFoundError:
from tkinter import *
from tkinter import messagebox
else:
print("tkinter error")
input()
sys.exit()
Running my script as .py or .pyw works without problems. But when I make and .exe out of it with cx_Freeze, the exe throws the error:
And why is that? how to solve this?
Thanks...
EDIT:
Also my setup.py:
import sys
import os
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = r"C:\Python\Python36-32\tcl\tcl8.6"
os.environ['TK_LIBRARY'] = r"C:\Python\Python36-32\tcl\tk8.6"
base = None
executables = [Executable("toolbar.py", base=base)]
packages = []
options = {
'build_exe': {
'packages':packages,
},
}
setup(
name = "Desktop Toolbar",
options = options,
version = "1.0",
description = " ",
executables = executables
)
Related
I am programming on Win 7 in Spyder/Anaconda. And I am having trouble converting my py into an exe. For background, my program .py has a few csv files it takes data from, asks the user for 4 integers, and generates a plot in matplotlib. It imports the packages below.
I was able to execute something like this (How can I convert a .py to .exe for Python?) but my situation isn't working when I start to use my code.
If I include "matplotlib" into the packages list, I get "KeyError: 'TCL_Library". What is this error and how do I fix it? Adding "os" works for reference.
In my program py, I use: import os, from os import listdir, import pylab, import matplotlib.pyplot as plt, import numpy as np, import matplotlib, import random. Do I leave these in my program py or move them to setup and how do I include the "from xxx" items in the packages array?
import os
from cx_Freeze import setup, Executable
base = None
executables = [Executable("try1.py", base=base)]
cwd = os.getcwd()
f_3_to_3=cwd+'\\' + '3_to_3.csv'
packages = ["idna", "matplotlib"]
options = {
'build_exe': {
"include_files": (f_3_to_3),
'packages':packages,
},
}
setup(
name = "FirstBuild",
options = options,
version = "0",
description = 'This is cool',
executables = executables
)
Using this for my setup file worked. Note, I had to fix directory for tk and tcl along with reinstalling them
import os
from cx_Freeze import setup, Executable
import sys
base = None
os.environ['TCL_LIBRARY'] = "C:\\ProgramData\\Anaconda3\\Library\\lib\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\ProgramData\\Anaconda3\\Library\\lib\\tk8.6"
executables = [Executable("MyPyFile.py", base=base)]
packages = ["idna", "os", "numpy", "numpy.core._methods", "matplotlib", "random"]
options = {
'build_exe': {
"includes": ["numpy.core._methods", "numpy", "tkinter"],
"include_files": [r'C:\ProgramData\Anaconda3\Library\plugins\platforms'],
'packages':packages,
},
}
setup(
name = "FirstBuild",
options = options,
version = "0",
description = 'This is cool',
executables = executables
)
I created a python 3 application that has a tkinter GUI and selenium action upon clicking a button. Here is the setup.py file:
from cx_Freeze import setup, Executable
import sys
import os
from pathlib import Path
buildOptions = {"include_files":['execute.py'], "packages": ['encodings'], "includes": ['numpy.core._methods', 'numpy.lib.format'], "excludes": []}
if sys.platform=='win32':
base = "Win32GUI"
else:
base=None
executables = [
Executable('bot_gui.py', base=base)
]
home_path = str(Path.home())
user_txt_path = []
if sys.platform=='win32':
print("windows detected")
user_txt_path.append('\\user.txt')
else:
print("macos detected")
user_txt_path.append('/user.txt')
#for initialization
f = open(home_path + user_txt_path[0], "w+")
for i in range(12):
f.write("---\n")
setup(name='tachysloth',
version = '1.0',
description = 'test',
options = dict(build_exe = buildOptions),
executables = executables)
The problem is when I run python setup.py build, everything works fine; but when I run python setup.py bdist_mac, the GUI works when you click on the application (called tachysloth-1.0 below)
but when I click on a button to in the GUI to open google.com on Chrome, the button does not do anything.
If you need more information to assess this problem, please let me know and I will provide that information as soon as possible.
Thank you again.
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
)
Trying to compile a Python 3.3 application but running into problems after compiling it to win32 exe using cx_freeze on Windows 7.
Example:
Test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import tkinter.messagebox
cl_parser = argparse.ArgumentParser(
description='Test app Command Line Parameters')
cl_parser.add_argument('--version', action='version', version='%(prog)s 1.0')
cl_parser.add_argument('-s', '--show', help='show simple message box',
action='store_true')
cl_args = cl_parser.parse_args()
if cl_args.show:
tkinter.messagebox.showinfo(title='Simple Message', message='Hi There')
Cx_Freeze Script
import sys
from cx_Freeze import setup, Executable
import shutil
#Remove Build/Dist Folder Before Compile
args = None
print('Removing Old Folders...')
try:
for args in sys.argv:
if args.find('build_exe') != -1:
shutil.rmtree('build', ignore_errors=True)
elif args.find('bdist_msi') != -1:
shutil.rmtree('dist', ignore_errors=True)
except:
pass
finally:
del args
print('Folders Removed')
base = None
if sys.platform == 'win32':
base = 'Win32GUI'
options = {
'build_exe': {
'includes': 'atexit',
'include_msvcr': True
}
}
executables = [
Executable('Test.py', base=base, targetName='Test App.exe')
]
setup(name='Test App',
version='1.0',
description='Test App',
options=options,
executables=executables)
After the successful compile I try a few command line tests on the exe:
Test App.exe -s (This successfully shows the messagebox)
Test App.exe -h or TestApp.exe --version (Fails with AttributeError: 'NoneType' Object has no attribute 'write')
Is there a way that I can make it so that this will work? I am trying to create a PyQt4 application and don't want to have to compile this as a console application.
Your feedback would be appreciated
P.S. Yes I know i've included an example with tkinter but this is for demo purposes only.
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"]