Python 3.4 GUI single executable - python

Today I've started learning python. I only ever used PHP for various things and never had to bother with building exe files.
Using some internet Python programming tutorials and a little of my own editing I came up with random "How many times you've clicked" application as shown below
import winsound
from tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.pack()
self.counts = 0
self.create_widgets()
def create_widgets(self):
Label(self, text = "Test Label").pack()
self.button = Button(self, text = "click", command = self.update_text).pack()
self.result = Label(self, text = "Clicked 0 times")
self.result.pack()
def update_text(self):
self.counts += 1
self.result["text"] = "Clicked " + str(self.counts) + " times"
winsound.PlaySound('sound1.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
root = Tk()
root.title("Title")
root.geometry("300x120")
app = Application(root)
root.mainloop
Application works fine but the problems started when I tried to compile it to a single exe file for a convenience reasons as I intend to write small "making something a bit easier" programs.
Py2Exe doesn't want to compile the program with bundle_files 1 at all.
PyInstaller did compile it with --onefile, but upon executing, application gives you nothing more than tkinter errors.
Is there a way of creating small one exe files with GUI or is it a dead end?
I'm not going to lie but I really loved the idea of learning python and being able to use it in both web and desktop applications which wasn't very possible in PHP.
I'm using Python 3.4 and tested builtin py2exe and development PyInstaller for Python 3.3 - 3.4.
Edit:
Sample setup.py for py2exe and the error
from distutils.core import setup
import py2exe
setup( windows=[{"script": "text.py"}],
options = {"py2exe": {"bundle_files": 1}
})
Error
C:\Users\SEJBR\Desktop\Python>python setup.py py2exe
running py2exe
1 missing Modules
------------------
? readline imported from cmd, code, pdb
OOPS: tkinter 2
PyInstaller compilation error
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'Tkinter'
2515 ERROR: TCL/TK seams to be not properly installed on this system

Well the workaround was quite simple.. I downgraded to Python 2.7.9 and PyInstaller compiled application perfectly with no problems.
I just used
from __future__ import print_function
from __future__ import division
To use Python 3.X print function and apply division changes. If anyone comes up with real fix please answer the question.

Related

Getting "OpenSSL.crypto.Error: [] when running an exe created by pyinstaller, the error seems to come from something related to selenium wire

I have a python script created with selenium wire and wxpython. The script runs fine on my computer and another co-worker's computer(who also has python installed). The idea for this app is to be able to work on other's computers without having to install anything else(if possible).
Script:
import wx
#PyProvider imports browser factory for choosing browser
from PyProvider import *
def __init__(self):
super().__init__(parent=None, title='Interceptor')
wx.Frame.__init__(self, None)
panel = wx.Panel(self)
self.Show()
self.StartBtn = wx.Button(panel, -1, "Start", pos=(3, 10))
self.StartBtn.Bind(wx.EVT_BUTTON,self.StartClicked)
self.driver = BrowserFactory("Chrome", False)
print("App Running")
def StartClicked(self, event):
self.driver.get('https://google.com')
if __name__ == '__main__':
app = wx.App()
frame = MyFrame()
app.MainLoop()
I then used pyinstaller to compile into an exe:
pyinstaller --onefile main.py
Everything runs and works great on my computer.
When I try to run the exe on someone else's computer(no python or anything installed) they were getting an error about a missing certificate(ca.crt). Which i fixed following instructions on this thread:
https://github.com/wkeeling/selenium-wire/issues/402
What I did from this thread was go to C:\Users\USER\AppData\Local\Temp.seleniumwire and made a cert and key file using the certificate & key contained in the file "seleniumwire-ca.pem". I then added these two files to where my script was and ran:
pyinstaller --add-data ca.crt;seleniumwire --add-data ca.key;seleniumwire --onefile main.py
This solved the certificate issue, but now when they run it, it shows this error
OpenSSL.crypto.Error:[]
I updated seleniumwire and tried installing pyOpenSSL as well, still same issue.
Sorry for the bad screenshot(it was from a video taken of the error) but that contains the stack trace showing it has to do with selenium-wire. I cant find any information about it online and have no idea how to fix it(I am really new to python)

Mac cxFreeze app quits unexpectedly when trying to open

I am trying to convert a python script to a mac app so I can distribute it. I'm using cxFreeze to do this. After creating the app, I try to open it but it says the app quit unexpectedly and shows some report.
(code signature invalid (errno=1)
usr/local/lib/Python (no such file)
---
my script at.py:
import tkinter as tk
from tkinter import font
window = tk.Tk()
width=1
window.title('test')
window.geometry("425x500")
label_speed = tk.Label(
text="Speed"
)
label_speed.grid(row=1, column=1, columnspan = 5, stick="w")
window.mainloop()
And then my setup.py
from cx_Freeze import Executable, setup
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [Executable("at.py", base=base)]
setup(
name="test",
version="0.1",
description="just for testing",
executables=executables,
)
I used the following commands to make the mac bundle or app.
python3 setup.py build then
python3 setup.py bdist_dmg
I had to use python3 instead of python because it wasn't working for me.
Thanks in advance for any tips and answers
There might be two different things going on. The first thing I know I have run into with cx_freeze is that it tried to map to where it thinks the python 2.x folder should be even if I specify to run on python 3.x. The other thing might be it was downloaded on to a different path. type $ where python to see where the file path should be. If you do $ open $FILEPATH and you see that its using python3 it might be worth reaching out to the maintainer of cx_freeze and see if they have any advice.

My PyQt app runs fine inside Idle but throws an error when trying to run from cmd

So I'm learning PyQt development and I typed this into a new file inside IDLE:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def window():
app = QApplication(sys.argv)
win = QDialog()
b1 = QPushButton(win)
b1.setText("Button1")
b1.move(50,20)
b1.clicked.connect(b1_clicked)
b2=QPushButton(win)
b2.setText("Button2")
b2.move(50,50)
QObject.connect(b2,SIGNAL("clicked()"),b2_clicked)
win.setGeometry(100,100,200,100)
win.setWindowTitle("PyQt")
win.show()
sys.exit(app.exec_())
def b1_clicked():
print("Button 1 clicked")
def b2_clicked():
print("Button 2 clicked")
if __name__ == '__main__':
window()
The app does what is supposed to, which is to open a dialog box with two buttons on it, when run inside IDLE. When I try to run the same program from cmd I get this message:
Traceback (most recent call last):
File "C:\Python34\Basic2buttonapp.py", line 2, in
from PyQt4.QtCore import *
ImportError: No module named 'PyQt4'
I've already tried typing python.exe inside cmd to see if Im running the correct version of python from within the cmd, but this does not seem to be the problem. I know it has to do with the communication between python 3.4 and the module, but it seems weird to me that it only happens when trying to run it from cmd.
If anyone has the solution I'll be very thankful.
This is because when running from the command line you're using a different version of Python to the one in IDLE (with different installed packages). You can find which Python is being used by running the following from the command line:
python -c "import sys;print(sys.executable)"
...or within IDLE:
import sys
print(sys.executable)
If those two don't match, there is your problem. To fix it, you need to update your PATH variable to put the parent folder of the Python executable referred to by IDLE at the front. You can get instructions of how to do this on Windows here.

Py2exe compiles properly but the built application doesn't work

I am using Python 2.7 to build my application. Within it, I used few packages which are numpy, scipy, csv, sys, xlwt, time, wxpython and operator.
All the above packages are in 64-bit, and I am using python 2.7(64-bit version) in Aptana Studio 3(64-bit version) in Windows 7 Professional (64-bit version).
At last, I'd like to compile my project to an application using following code, the file name is py2exeTest.py:
from distutils.core import setup
import numpy # numpy is imported to deal with missing .dll file
import py2exe
setup(console=["Graphical_Interface.py"])
Then in cmd, I switched to the directory of the project and used following line to compile it:
python py2exeTest.py py2exe
Everything goes well, it generates an application under dist directory, and the application name is Graphical_Interface.exe.
I double clicked it, but there is a cmd window appears, and a python output windows flashes, then both of them disappeared. I tried to run the application as an administrator, the same outcome I've had.
May I know how to work this out?
Thanks!
EDIT:
I've managed to catch the error information that flashes on the screen. The error info I had is:
Traceback (most recent call last):
File "Graphical_Interface.py", line 397, in <module>
File "Graphical_Interface.py", line 136, in __init__
File "wx\_core.pyc", line 3369, in ConvertToBitmap
wx._core.PyAssertionError: C++ assertion "image.Ok()" failed at ..\..\src\msw\bitmap.cpp(802) in wxBitmap::CreateFromImage(): invalid image
I used one PNG image in the project, the code is like follows:
self.workflow = wx.Image("Work Flow.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.StaticBitmap(self.panel_settings, -1, self.workflow, (330,270), (self.workflow.GetWidth(), self.workflow.GetHeight()))
I tried to comment the above chunk out from the project, and the application works properly. However, I need the image to show up in the application.
May I know how to deal with it?
Thanks.
Hiding console window of Python GUI app with py2exe
When compiling graphical applications you can not create them as a console application because reasons (honestly can't explain the specifics out of my head), but try this:
from distutils.core import setup
import numpy
import py2exe
import wxpython
setup(window=['Graphical_Interface.py'],
options={"py2exe" { 'boundle_files' : 1}})
Also consider changing to:
http://cx-freeze.sourceforge.net/
It works with Python3 and supports multiple platforms.
A cx_freeze script would look something like:
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
includefiles = ['/folder/image.png']
setup( name = "GUIprog",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options, 'include_files' : includefiles},
executables = [Executable("Graphical_Interface.py", base=base)])
No worries, I've got the solution.
It turns out that the image is in the project folder rather than in the dist folder. So I have two solutions:
Copy the image into dist folder
Include the full path of the image in the code.
Thanks for your help.

Help with Tkinter in py2exe

I'm trying to convert a basic tkinter GUI program to an .exe using py2exe. However I've run into an error using the following conversion script.
# C:\Python26\test_hello_con.py py2exe
from distutils.core import setup
import py2exe
setup(windows=[r'C:\Python26\py2exe_test_tk.py'])
C:\Python26\py2exe_test_tk.py is the following code
import Tkinter as tk
root = tk.Tk()
root.title("Test")
label1 = tk.Label(root,text="Hello!",font=('arial', 10, 'bold'), bg='lightblue')
label1.pack(ipadx=100, ipady=100)
root.mainloop()
This is the error I get when I try to run the newly created .exe
Traceback (most recent call last):
File "py2exe_test_tk.py", line 4, in <module>
File "Tkinter.pyc", line 1643, in __init__
_tkinter.TclError: Can't find a usable init.tcl in the following directories:
{C:/Users/My_Name/lib/tcl8.5} {C:/Users/My_Name/lib/tcl8.5} C:/Users/lib/tcl8.5 {C:/Users/My_Name/library} C:/Users/library C:/Users/tcl8.5.8/library C:/tcl8.5.8/library
This probably means that Tcl wasn't installed properly.
I'm pretty sure it's something in my conversion script thats giving me problems. What did I omit? Or does someone have an example of what the conversion script would look like for a tkinter GUI program? Also is it possible to divert the output .exe files to my desktop?
EDIT:
The error report said that I was missing init.tcl from {C:/Users/My_name/lib/tcl8.5}. So i made that directory and put a copy of init.tcl there. Now when I try to run the .exe it states that MSVCR90.dll is missing from my computer and is needed to run my program.
Also this is python 2.6.5 on Windows 7.
Such errors in Unix world are usually due to incorrect PATH settings or/and incorrectly installed third party modules (the GUI ones you're using). Have you seen this post: py2exe fails to generate an executable ?

Categories