Convert Tkinter py file into EXE file - python

im trying to convert my tkinter file into EXE using cx_freeze, but i got this error all the time
the error
translation of the hebrew part: module didnt found
my setup file code is:
import sys
from cx_Freeze import setup, Executable
import os
os.environ['TCL_LIBRARY'] = "C:\\Users\\royreznik\\AppData\\Local\\Programs\\Python\\Python36-32\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\Users\\royreznik\\AppData\\Local\\Programs\\Python\\Python36-32\\tcl\\tk8.6"
build_exe_options = {"includes": ["tkinter"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "simple_Tkinter",
version = "0.1",
description = "Sample cx_Freeze Tkinter script",
options = {"build_exe": build_exe_options},
executables = [Executable("tal1.py", base = base)])
and my main file is:
from tkinter import *
root = Tk()
Entry1 = Entry(root)
Entry2 = Entry(root)
Entry1.grid(row=0)
Entry2.grid(row=1)
Label1 = Label(root, text="null")
Label1.grid(row=4)
def funca():
phrase = Entry1.get()
words = phrase.split()
wordCount = 0;
for word in words:
if word == Entry2.get():
wordCount = wordCount+1
Label1.configure(text=wordCount)
btn = Button(root, text="get Num",command=funca)
btn.grid(row=3)
root.mainloop()
whats the problem?

In your Python directory's DLLs folder you will find tk86t.dll and tcl86t.dll. You have to copy them into the build folder with the main.py you want to compile.
Then you have to add these two files to the include_files parameter in your setup.py.
Now, your setup.pyshould look like something like this :
import os
from cx_Freeze import setup, Executable
os.environ['TCL_LIBRARY'] = 'c:/python36/tcl/tcl8.6'
os.environ['TK_LIBRARY'] = 'c:/python36/tcl/tk8.6'
buildOptions = dict(
packages = [],
excludes = [],
include_files=['c:/python36/DLLs/tcl86t.dll', 'c:/python36/DLLs/tk86t.dll']
)
import sys
base = 'Win32GUI' if sys.platform=='win32' else None
executables = [
Executable('editor.py', base=base)
]
setup(name='editor',
version = '1.0',
description = '',
options = dict(build_exe = buildOptions),
executables = executables)
Of course you may have to adapt the directories paths to make it work.

Related

Include entire folders in cx_Freeze with pygame

I have been following a tutorial on how to make a cx_freeze setup for pygame folders. Here is what I have come up with...
import cx_Freeze
executables = [cx_Freeze.Executable("mainGame - Copy.py")]
cx_Freeze.setup(
name = "Cave",
version = "1.0",
author = "Owen Pennington",
options = {"build_exe": {"packages":["pygame"], "include_files":["floor_heart.wav"]}},
executables = executables
)
However the rest of my files are in folders. Then there are folders inside these folders. For example I have a folder (path directory) C:CaveGame\Sprites and this folder holds many other folders, C:CaveGame\Sprites\Floors, C:CaveGame\Sprites\Lava ect... Then I also have a folder C:CaveGame\Music which holds all my music files and sound effects. How can I get these all to work inside the setup???
You just need to include the upper-level directory item in your options dictionary:
setup(name='Widgets Test',
version = '1.0',
description = 'Test of Text-input Widgets',
author = "Fred Nurks",
options = { "build_exe": {"packages":["pygame"], "include_files":["assets/", "music/"] } },
executables = executables
)
The above example will include the files assets/images/blah.png and music/sounds/sproiiiing.ogg along with their correct directories. Everything under that top-level folder is pulled into the lib/.
When you go to load these files, it's necessary to work out the exact path to the files. But the normal method to do this does not work with cxFreeze. Referencing the FAQ at https://cx-freeze.readthedocs.io/en/latest/faq.html ~
if getattr(sys, 'frozen', False):
EXE_LOCATION = os.path.dirname( sys.executable ) # frozen
else:
EXE_LOCATION = os.path.dirname( os.path.realpath( __file__ ) ) # unfrozen
Obviously you need the modules sys and os.path for this.
Then when loading a file, determine the full path with os.path.join:
my_image_filename = os.path.join( EXE_LOCATION, "assets", "images", "image.png" )
image = pygame.image.load( my_image_filename ).convert_alpha()
EDIT: If you're building under Windows, you will need to also include the Visual C runtime: https://cx-freeze.readthedocs.io/en/latest/faq.html#microsoft-visual-c-redistributable-package . Add include_msvcr to options.
options = { "build_exe": { "include_msvcr", "packages":["pygame"] #...

Image directories and cx_Freeze

So basically i want to convert a .py script into an executable file. The only problem is is that the setup.py file has to be in the same directory as the image and sound files, while my game file is in a directory above that with the setup.py.
How do i edit the setup file so that i dont have to go around and change all the code in my game file? If needed i'll edit the game file but preferably not.
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
snd_dir = path.join(path.dirname(__file__), 'snd')
#ways i load in images:
background = pygame.image.load(path.join(img_dir,
"background.jpg")).convert()
alien_images = []
alien_list = ['alien1.png', 'alien2.png']
for img in alien_list:
alien_images.append(pygame.image.load(path.join(img_dir,
img)).convert())`
This is the setup file i have now. Apart from it being unable to find the images and sounds of course, it is error free.
import cx_Freeze
executables = [cx_Freeze.Executable("Shmup.py")]
cx_Freeze.setup(
name = "Shoot 'm up!",
options = {"build_exe": {"packages":["pygame"],
"include_files": ["alien1.png", "alien2.png",
"background.jpg", "laser1.png",
"powerUp.png", "shield.png",
"regularExplosion00.png",
"regularExplosion01.png",
"regularExplosion02.png",
"regularExplosion03.png",
"regularExplosion04.png",
"regularExplosion05.png",
"regularExplosion06.png",
"regularExplosion07.png",
"regularExplosion07.png",
"regularExplosion08.png",
"regularExplosion09.png",
"ship1.png",
"sonicExplosion00.png",
"sonicExplosion01.png",
"sonicExplosion02.png",
"sonicExplosion03.png",
"sonicExplosion04.png",
"sonicExplosion05.png",
"sonicExplosion06.png",
"sonicExplosion07.png",
"sonicExplosion08.png",
"sonicExplosion09.png",
"Expl.wav", "Expl2.wav",
"Music.ogg", "Pew.wav",
"Powerup.wav", "Rumble.ogg"]}},
executables = executables
)
You can include a relative directory in your "include_files" directive. Something like this:
include_files = [("game_assets", "assets")]
That will copy all of the files in the directory "game_assets" to a target directory "assets". You can use whatever you wish for the names, of course!

CX_Freeze: Python.exe not responding

I am trying to convert my text editor into an exe to sell it, but Windows says that python.exe is not responding when I try to convert it in cmd.
My file name is arshi.py.
Below is my setup.py:
import sys
from cx_Freeze import setup, Executable
base = None
if (sys.platform == "win32"):
base = "Win32GUI"
exe = Executable(
script = "arshi.py",
icon = "icon.PNG",
targetName = "Arshi.exe",
base = base
)
setup(
name = "Arshi Editor",
version = "0.1",
description = "A lightweight text editor for Python",
author = "Henry Zhu",
options = {'build_exe': {"packages": ["pygments"]}},
executables = [exe]
)
cx_freeze doesn't accept .png files, but rather only .ico files. Converting the .png file to an .ico file worked beautifully for me.

PyQt and py2exe: no sound from QSound after compiling to .exe

I have problem with playing .wav sound with QSound.play() after compiling to exe (I'm using Python 3.4.3, PyQt 5.4.1 and py2exe 0.9.2.0).
setup.py code:
from distutils.core import setup
import py2exe
setup(
windows=[
{
"script": "main_app.py",
"icon_resources": [(0, "favicon163248.ico")]
}
],
data_files=[
(
'sounds', ['sounds\Siren.wav']
)
],
options={"py2exe": {"includes": ["sip"], "dist_dir": "MyProject"}}
)
What have i tried:
Relative path
sound = QSound("sounds/Siren.wav")
sound.play() #works when simply running, doesn't work when compiling to exe
Path to executable file (main_app.exe)
sound = QSound(os.path.dirname(sys.executable) + "\sounds\Siren.wav")
sound.play() #doesn't work when compiling to exe
Absolute path
sound = QSound("C:\\path\\to\\project\\MyProject\\sounds\\Siren.wav")
sound.play() #works when simply running, doesn't work when compiling to exe
Resources
resources_qrc.qrc code:
<RCC>
<qresource prefix="media">
<file>Siren.wav</file>
<file>favicon163248.ico</file>
</qresource>
</RCC>
then converted to resources.py with pyrcc5
from resources import *
...
sound = QSound(':/media/Siren.wav')
sound.play() #works when simply running, doesn't work when compiling to exe
Copy form resource to hard drive on the fly
QFile.copy(":/media/Siren.wav", "sounds/Siren.wav")
sound = QSound("sounds/Siren.wav")
sound.play() #still doesn't work after making exe!
After spending pretty much time on it, I gave up.
Any help would be appreciated.
I use python 2.7 and cx_Freeze 4.3.1 and PyQt4
#-*- coding: utf-8-*-
__author__ = 'Aaron'
from cx_Freeze import setup, Executable
import sys
if sys.platform == "win32":
base = "Win32GUI"
includefiles= ['icons','Sound','imageformats']
includes = ['sip', 'PyQt4.QtCore']
setup(
name = u"Your Programe",
version = "1.0",
description = u"XXXX",
options = {'build_exe': {'include_files':includefiles}},
executables = [Executable("Your programe name.py" ,base = base, icon = "XXX.ico")])
I had the same problem too, with Python 3.4.3, PyQt 5.5.1, py2exe 0.9.2.2.
Problem is not in wrong file path.
If you call:
QAudioDeviceInfo.availableDevices(QAudio.AudioOutput)
from .exe, the returned list will be empty.
You should add foder: "\audio" from "site-packages\PyQt5\plugins" to the directory with your output .exe file, and sound will work.
Here is my setup.py file:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe
import sys
import os, os.path
import zipfile
import shutil
def get_exe_name(f):
dirname, filename = os.path.split(os.path.abspath(f))
return os.path.split(dirname)[-1].lower()
def get_name(name):
idx = name.find('.')
if idx != -1:
return name[:idx]
return name
def build(__version__, __appname__, main_module = 'main.py', dest_base='main', icon='images\\main.ico'):
#exec('from ' + get_name(main_module) + ' import __version__, __appname__')
try:
shutil.rmtree('dist')
except:
print ('Cann\'t remove "dist" directory: {0:s}'.format(str(sys.exc_info())))
if len(sys.argv) == 1:
sys.argv.append('py2exe')
options = {'optimize': 2,
# 'bundle_files': 0, # create singlefile exe 0
'compressed': 1, # compress the library archive
'excludes': ['pywin', 'pywin.debugger', 'pywin.debugger.dbgcon', 'pywin.dialogs', 'pywin.dialogs.list', 'os2emxpath', 'optparse', 'macpath', 'tkinter'],
'dll_excludes': ['w9xpopen.exe', 'mapi32.dll', 'mswsock.dll', 'powrprof.dll', 'MSVCP90.dll', 'HID.DLL'], # we don't need this
'includes': ['sip', 'locale', 'calendar', 'logging', 'logging.handlers', 'PyQt5', 'PyQt5.QtCore', 'PyQt5.QtGui', 'PyQt5.QtMultimedia', 'PyQt5.QtNetwork', 'PyQt5.QtPrintSupport'],
}
#datafiles = [('platforms', ['C:\\Python34\\Lib\\site-packages\\PyQt5\\plugins\\platforms\\qwindows.dll']),]
import PyQt5
datafiles = [('platforms', [PyQt5.__path__[0] + '\\plugins\\platforms\\qwindows.dll']), ('audio', [PyQt5.__path__[0] + '\\plugins\\audio\\qtaudio_windows.dll']),]
dirs = ['images', 'docs', 'ssl', 'sounds', 'p2ini', 'lib', 'config']
for d in dirs:
try:
for f in os.listdir(d):
f1 = d + '\\' + f
if os.path.isfile(f1): # skip directories
datafiles.append((d, [f1]))
except:
print ('Cann\'t find some files in directory "{0:s}": {1:s}'.format(d, str(sys.exc_info())))
setup(version = __version__,
description = __appname__,
name = '{0:s} {1:s} application'.format(__appname__, __version__),
options = {'py2exe': options},
zipfile = None,
data_files = datafiles,
windows = [{'icon_resources':[(1,'images\\main.ico')], 'script':main_module, 'dest_base':dest_base}] if icon else [{'script':main_module, 'dest_base':dest_base}],
scripts = [main_module],
#console = [{'icon_resources':[(1,'images\\main.ico')], 'script':main_module, 'dest_base':dest_base}] if icon else [{'script':main_module, 'dest_base':dest_base}],
)
And example code for call setup.py functions:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from setup import get_name, get_exe_name, build
MAIN_MODULE = 'main.py'
exec('from ' + get_name(MAIN_MODULE) + ' import __version__, __appname__')
build(__version__, __appname__, MAIN_MODULE, dest_base=get_exe_name(__file__))

cx_freeze : compiled tkinter app is not lauching

It is the first time I'm using cx_freeze and I really need help on this, I've been looking everywhere but i can't find an answer.
I don't have any error during the compiling process, but the executable file just doesn't do anything. Could someone please explain me why?
Here is my project structure:
Application
setup.py
application.py (Tkinter app that import 2 functions from cell.py)
logo.jpg
favicon.ico
responsible.xls
modules:
cell.py (all the work is done in this file)
I don't know where to include the file cell.py in setup, for now it's in a file Modules. And i'm not sure if Tkinter should be include or exclude.
Here is the file setup.py:
import sys
from cx_Freeze import setup, Executable
executables = [
Executable("application.py")
]
buildOptions = dict(
compressed = True,
includes = ["sys","re","PIL","ttk","xlrd","xlutils","datetime","string","Tkinter"],
include_files = ["responsible.xls","favicon.ico","logo.jpg"],
excludes = []
path = sys.path + ["modules"]
)
setup(
name = "test",
version = "1.1.1.0",
description = "test",
options = dict(build_exe = buildOptions),
executables = executables
)
You add the directories you want to include with the include_files option.
So this part of your code should be like this:
buildOptions = dict(
compressed = True,
includes = ["sys","re","PIL","ttk","xlrd","xlutils","datetime","string","Tkinter"],
include_files = ["responsible.xls","favicon.ico","logo.jpg", "modules"],
excludes = []
path = sys.path + ["modules"]
)

Categories