How to include images into exe generated by PyInstaller in Python - python

I use PyQt5 to develop a GUI application in python, and that works. Now, I would like to generate exe file using PyInstaller, but I don't know how to include image files into exe file. I mean I wish the exe file doesn't rely on external image files any more.
I have tried the method below, but it seems doesn't work for me.
Pyinstaller and --onefile: How to include an image in the exe file
following is part of my code:
my code:
class DASH(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.animation = Animation()
self.setCentralWidget(self.animation)
exitAct = QAction(QIcon(r'car.png'), 'Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(self.close)
spec file:
# -*- mode: python -*-
block_cipher = None
a = Analysis(['C:\\Jiawei\\Work\\python_simulation_V2\\python_visualization.py'],
pathex=['C:\\Users\\Lujia'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
a.datas += [('car.png','C:\\Jiawei\\Work\\python_simulation_V2\\images\\car.png', 'Data')]
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='python_visualization',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )

Related

How to generate .exe of a kivymd application without console properly?

I'm trying to generating a .exe of my kivymd code. I have coded a really simple code, because i was trying to learn how to do this.
My code is as follows:
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.screen import Screen
class Demo(MDApp):
def build(self):
self.screen = Screen()
self.l1 = MDLabel(
text = "My Label"
)
self.screen.add_widget(self.l1)
return self.screen
if __name__ == "__main__":
Demo().run()
Really simple.
So i'm using a .spec like this:
# -*- mode: python ; coding: utf-8 -*-
import os
from kivy_deps import sdl2, glew
block_cipher = None
from kivymd import hooks_path as kivymd_hooks_path
current_path = os.path.abspath('.')
icon_path = os.path.join(current_path, 'imagens', 'icone.ico')
a = Analysis(['main.py'],
pathex=[current_path],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[kivymd_hooks_path],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
name='Eaton',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
icon=icon_path,
console=False )
My code file name is main.py and my .spec is main.spec.
So my problem is, when I use the console=True, this code and .spec works fine and create a good .exe, but when I use console=False the aplication returns error.
If someone can help me I will be very thankful.

Black screen for kivy based windows exe generated using pyinstaller

I have a small application based on Kivy and python. it is working fine if I run it form Visual studio code. But if I generate exe form it using pyinstaller, the generated exe is showing black screen.
Below is my .py file:
from kivy.app import App
#from kivy.core import text
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
class Demo(GridLayout):
name = ObjectProperty(None)
age = ObjectProperty(None)
def on_click(self):
print("My name is {} and my age is {}".format(self.name.text, self.age.text))
self.name.text = ""
self.age.text = ""
class DemoClassApp(App):
def build(self):
return Demo()
if __name__ == "__main__":
DemoClassApp().run()
Below is my kivy file :
# Filename: democlass.kv
<Demo>:
#cons: 2
rows: 5
#row_default_height: 40
size: root.width, root.height
name : name
age : age
Label:
text: "Enter your Name"
font_size: 50
TextInput:
id : name
text: ""
font_size: 50
Label:
text: "Enter your Age"
font_size: 50
TextInput:
id : age
text: ""
font_size: 50
Button:
text: "submit"
on_press : root.on_click()
Below is the .spec file:
from kivy_deps import sdl2, glew
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['app1.py'],
pathex=['C:\\Users\\sj3kc0\\Desktop\\kivy'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='app1',
debug=True,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True)
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
strip=False,
upx=True,
upx_exclude=[],
name='app1')
I am new to kivy. let me know if I am doing anything wrong. The ,spec file generated is modified little bit. The default generated file is producing an exe which is not even lauchning. But here with the modified .spec file, the exe is launching but the widgets are not available.
the black screen that's mean the app does not read the UI in the kv file so you need to include it in the spec file inside datas list
from kivy_deps import sdl2, glew
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['app1.py'],
pathex=['C:\\Users\\sj3kc0\\Desktop\\kivy'],
binaries=[],
datas=[('*.kv':'.')],# here we add all the kv files are placed in the same app1.py file level assumed that your kv file is
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='app1',
debug=True,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True)
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
strip=False,
upx=True,
upx_exclude=[],
name='app1')
finally you can run pyinstaller pyinstaller.spec
and if you like to more information about pyinstaller spec you can see this link here

Python 2.7 single executable for python kivy GUI with PyInstaller

I am trying unsuccessfully to wrap up my kivy GUI application into a single executable with pyinstaller. Whey I run PyInstaller, it creates a single executable, but when I run it I get a "fatal error" saying "Failed to execute script myApp". I am using python 2.7 on windows. Here is my directory setup:
GUI_DEV\
-myApp_style.kv (this is my kivy file)
-myApp.py (this is my main script)
-ico.ico (this is my icon file)
-myImage.png (this is an image used by myApp.py)
rel\
-myApp.spec (this is the spec file I am using with pyinstaller)
Here is my myApp.py code:
import kivy
#kivy.require("1.9.0")
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import sys, os
def resourcePath():
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS)
return os.path.join(os.path.abspath("."))
Builder.load_file('myApp.kv')
class designerLayout(GridLayout):
part = "123"
def update(self):
self.part = value
self.id_test.text = "hello world: "+str(self.part)
return
def spinner_clicked(self, value):
self.part = value
self.id_test.text = "hello world: "+str(self.part)
class myApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
Window.size = (930,780)
return designerLayout()
if __name__ == '__main__':
kivy.resources.resource_add_path(resourcePath()) # add this line
calcApp = myApp()
calcApp = myApp()
calcApp.run()
Here is my myApp.spec file:
# -*- mode: python -*-
from kivy.deps import sdl2, glew
block_cipher = None
a = Analysis(['..\\myApp.py'],
pathex=['C:\\GUI_DEV\\rel\\MyHiddenImports'],
binaries=None,
datas=None,
hiddenimports=['MyHiddenImports'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
a.datas += [('myApp_style.kv', '../myApp_style.kv', 'DATA')]
exe = EXE(pyz, Tree('C:\\GUI_DEV\\','Data'),
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
name='myApp',
debug=False,
strip=False,
upx=True,
console=False, icon='C:\\GUI_DEV\\ico.ico' )
I am then running the command:
python -m PyInstaller myApp.spec
from the GUI_DEV\rel directory.
Any ideas as to why this is not working? I am not getting any errors that point me to any specific problems.

kivy error: OSError: File data/fonts/Roboto-Regular.ttfs not found and also im on windows 8.1

"main.py"
from kivy.app import App
class WeatherApp(App):
pass
if __name__="__main__":
WeatherApp().run()
"weather.kv"
Label:
text: "hello world"
i am expecting a window with a black background and the words "hello world"
in the middle
For me I managed to solve
Editing the spec file like so:
# -*- mode: python ; coding: utf-8 -*-
from kivy_deps import sdl2, glew
block_cipher = None
a = Analysis(['hello.py'],
pathex=['C:\\Users\\<username>\\PycharmProjects\\<project_dir>'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
[],
exclude_binaries=True,
name='hello',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True )
coll = COLLECT(exe,
Tree('C:\\Users\\<username>\\PycharmProjects\\<project_dir>'),
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
strip=False,
upx=True,
upx_exclude=[],
name='hello')
by copying the kivymd dir C:\Users<username>\Anaconda3\envs<project_name>\Lib\site-packages\kivymd to your dist folder
Roboto-Regular.ttfs Not Found - Windows 8.1
Currently, in the Kivy config file, the default fonts used for widgets displaying any text defaults to [‘Roboto’, ‘data/fonts/Roboto-Regular.ttf’, ‘data/fonts/Roboto-Italic.ttf’, ‘data/fonts/Roboto-Bold.ttf’, ‘data/fonts/Roboto-BoldItalic.ttf’].
The latest version of Roboto can be found at https://github.com/google/roboto/releases
There is a typo error and indentation problem in your app. After fixing the problems, your app should works as shown in the example below.
Replace:
if __name__="__main__":
with:
if __name__ == "__main__":
Example
main.py
from kivy.app import App
class WeatherApp(App):
pass
if __name__ == "__main__":
WeatherApp().run()
weather.kv
#:kivy 1.10.0
Label:
text: "hello world"
Output

Python program with selenium(webdriver) Don't Work as single and noconsole exe file (pyinstaller)

The following is my python code:
## t.py ##
from tkinter import messagebox
from tkinter import *
from selenium import webdriver
def clicked():
iedriver = "C:\\Program Files\\Internet Explorer\\IEDriverServer.exe"
try:
driver=webdriver.Ie(iedriver)
except Exception as e:
messagebox.showerror("Error",e)
driver.get('www.baidu.com')
Top=Tk()
Button(Top,text='Click Me',command=clicked).pack()
Top.mainloop()
This works fine, but when I convert this to a single .exe file with PyInstaller(t.spec):
# -*- mode: python -*-
block_cipher = None
a = Analysis(['D:\\program\\Python\\t.py'],
pathex=['D:\\program\\Python'],
binaries=None,
datas=None,
hiddenimports=[],
hookspath=None,
runtime_hooks=None,
excludes=None,
win_no_prefer_redirects=None,
win_private_assemblies=None,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='t',
debug=False,
strip=None,
upx=False,
console=0 , icon='D:\\program\\Python\\logo\\t.ico')
It will prompt the following error when clicking the button to run:
Seems that IEDriver executable can't be recognized
When I change the option "console=0" to "console=1" in the spec file, IE can be run after clicking the button. Any idea why IE can't be run when "console=0" is set?
I think I fixed this by modifying the Service class in selenium package. I'm not sure whether this is a bug for selenium(2.47.3). The original code is only redirecting stdout and stderr but not stdin when it calls subprocess.Popen function.
I modified the code from:
self.process = subprocess.Popen(cmd,
stdout=PIPE, stderr=PIPE)
To:
self.process = subprocess.Popen(cmd, stdin=PIPE,
stdout=PIPE, stderr=PIPE)
Then the issue is gone.

Categories

Resources