auto-py-to-exe failed to execute script du to unhandled exception - python

enter image description herehi em trying to make exe file for my project using auto-py-installer, and when i launch it , i have an exception : No such file or directory : plotting.ui. i used Qt Designer for making UI i load 'plotting.ui' on my script.
from PyQt5.QtWidgets import QApplication,QDialog,QMainWindow,QLabel,QWidget,QFrame,QPushButton,QComboBox\
,QHBoxLayout,QFileDialog
import sys
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import numpy as np
import pandas as pd
from PyQt5 import uic
from pathlib import Path
from pykalman import KalmanFilter
from PyQt5 import QtGui
import os
class graph_kf_data(QMainWindow) :
def __init__(self):
super(graph_kf_data, self).__init__()
scriptDir = os.path.dirname(os.path.realpath(__file__))
self.setWindowTitle("DATA ANALYSIS APPLICATION")
self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep +'images/'+'logo.png'))
uic.loadUi('ploting.ui',self)
self.comboBox = self.findChild(QComboBox,'comboBox')
self.frame_4 = self.findChild(QFrame,'frame_4')
self.pushButton = self.findChild(QPushButton,'pushButton')
self.pushButton_2 = self.findChild(QPushButton,'pushButton_2')
#create a horizantal layout
self.horizantalLayout_7 = QHBoxLayout(self.frame_4)
self.horizantalLayout_7.setObjectName('horizantalLayout_7')
#create canvas
self.fugure = plt.figure()
self.canvas =FigureCanvas(self.fugure)
#add canvas
self.horizantalLayout_7.addWidget(self.canvas)
self.pushButton.clicked.connect(self.view_graphs)
self.pushButton_2.clicked.connect(self.upload)

Related

Exluding PyQT5 in cx_freeze to make library much smaller and exe startup much faster

how to make a EXE library much smaller in size and the exe startup faster?. My library is actually 580 MB and the startup time from the exe is around 10 seconds! Here is my main.py. Its imports data from interface. (sub program)
import sys
from datetime import datetime
from typing import Tuple
import numpy as np
import pandas as pd
from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtWidgets import (QWidget, QTableWidget, QTableWidgetItem)
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtGui import QImage
from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QKeySequence
from PyQt5.QtGui import QMovie
from PyQt5.QtGui import QPainter
from PyQt5.QtGui import QPen
from PyQt5.QtGui import QColor
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QTimer
from PyQt5.QtCore import Qt, QPoint
import cv2
import os
from sys import path
import shutil
import xlsxwriter
from tkinter import Tk, PhotoImage, Canvas
from interface import *
from line_detection import *
import openpyxl
from openpyxl.styles import Alignment, Font
import os.path
The header of interface.py looks like this:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import os.path
import pandas as pd
import numpy as np
from datetime import datetime
import xlsxwriter
import openpyxl
from openpyxl.styles import Alignment, Font
from openpyxl import load_workbook
In Inteface.py i do something like this:
MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
class Ui_Form(object):
def __init__(self):
self.show_label = True
self.show_groupbox = False
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(w, h)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.image_label1 = QtWidgets.QLabel(self.centralwidget)
self.image_label1.setGeometry(QtCore.QRect(0, 0, w, h))
self.image_label1.setText("")
self.image_label1.setObjectName("image_label1")
self.image_label1.setHidden(self.show_label)
self.image_label1.setDisabled(self.show_groupbox)
My cx_freeze (setup.py) looks like this. Its still including all packages and so on. How to make PyQT5 and other Packages much smaller when making a EXE
import sys
from cx_Freeze import setup, Executable
try:
from cx_Freeze.hooks import get_qt_plugins_paths
except ImportError:
include_files = []
else:
# Inclusion of extra plugins (new in cx_Freeze 6.8b2)
# cx_Freeze imports automatically the following plugins depending of the
# use of some modules:
# imageformats - QtGui
# platforms - QtGui
# mediaservice - QtMultimedia
# printsupport - QtPrintSupport
#
# So, "platforms" is used here for demonstration purposes.
include_files = get_qt_plugins_paths("PyQt5", "platforms")
# base="Win32GUI" should be used only for Windows GUI app
base = None
if sys.platform == "win32":
base = "Win32GUI"
build_exe_options = {
#[""]
"excludes": ["PyQt5.QtBluetooth",
"PyQt5.QtNetwork",
"PyQt5.QtNfc",
"PyQt5.QtWebChannel",
"PyQt5.QtWebEngine",
"PyQt5.QtWebEngineCore",
"PyQt5.QtWebEngineWidgets",
"PyQt5.QtWebKit",
"PyQt5.QtWebKitWidgets",
"PyQt5.QtWebsockets",
"PyQt5.QtSql",
"PyQt5.QtScript"],
"include_files": include_files,
}
bdist_mac_options = {
"bundle_name": "TEST",
}
bdist_dmg_options = {
"volume_label": "TEST",
}
executables = [Executable("main.py", base=base, target_name="TEST")]
setup(
name="TEST",
version="2.4",
description="TEST",
options={
"build_exe": build_exe_options,
"bdist_mac": bdist_mac_options,
"bdist_dmg": bdist_dmg_options,
},
executables=executables,
)

how matplotlib in pyqt5 using qt designer [duplicate]

I want to plot a figure with embedded matplotlib in PyQt.
I am using Qt Designer for the main window, and writing python code for the signal and slots connexion part.
So my code looks like this :
import sys
from PyQt4 import QtCore, QtGui, uic
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
qtCreatorFile = "main.ui" # my Qt Designer file
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.csvbutton.clicked.connect(self.plot)
def plot(self):
filePath="/path to csv file here"
df= pd.read_csv(str(filePath),index_col='date')
df.index = pd.to_datetime(df.index, unit='s')
ax = self.figure.add_subplot(111)
ax.hold(False)
ax.plot(df, '*-')
self.canvas.draw()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
My main problem is the connexion between the Qt Designer file and the python code, I couldn't set a canvas widget directly in Qt Designer and I'm still struggling to find where the error lays in my code.
Your help is very appreciated, thank you.
In order to use matplotlib in Qt Designer can not be done directly, for this we must promote a QWidget to use FigureCanvas or better a class that inherits from it as I show below, first we create a class called Canvas in file called canvas.py:
canvas.py
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
class Canvas(FigureCanvas):
def __init__(self, parent=None):
self.figure = plt.figure()
FigureCanvas.__init__(self, self.figure)
self.setParent(parent)
After creating the design through Qt Designer, we have all the elements we want, but where we want to place the argument we use the Widget element that is in Containers, and we name it canvas:
Then we promote it by right click and choose the option promoted to ...:
Obtaining what is shown in the following image, in Promoted Class Name we place Canvas as the name of the class, and in Header File we place canvas.h (in Header File the file.py file is placed, for example package.subpackage.file.h), then press Add and after Promote:
At the end we get a file structure similar to the following:
.
├── canvas.py
└── main.ui
Then we create the file main.py where we place your code with small variations:
main.py
import matplotlib
matplotlib.use('Qt4Agg')
import sys
from PyQt4 import QtCore, QtGui, uic
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
qtCreatorFile = "main.ui" # my Qt Designer file
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.csvbutton.clicked.connect(self.plot)
def plot(self):
filePath="data.csv"
df= pd.read_csv(str(filePath),index_col='date')
ax = self.canvas.figure.add_subplot(111)
ax.hold(False)
ax.plot(df, '*-')
self.canvas.draw()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
In the end we get the following:
You can find the complete project here
If you want to add the NavigationToolbar you can use the following code:
...
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
...
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.addToolBar(NavigationToolbar(self.canvas, self))
...

AttributeError: 'QWheelEvent' object has no attribute 'delta'

I am making a simple GUI using pyqt5. It runs fine, but when I open it and try to use the mouse's wheel, it crashes with the following error:
AttributeError: 'QWheelEvent' object has no attribute 'delta'.
Here is the code to reproduce the problem:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
class View(QGraphicsView):
def __init__(self):
super(View, self).__init__()
self.setRenderHint(QPainter.Antialiasing)
self.initScene(5)
def initScene(self,h):
self.scene = QGraphicsScene()
#self.setSceneRect(0, 100, 1400, 700) #this controls where the scene begins relative to the window
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.canvas.setGeometry(0,0,900,700)
#self.setSceneRect(0, 0, 2607, 700)
self.figure.subplots_adjust(left=0,right=1,bottom=0,top=1,wspace=0, hspace=0)
axes1 = self.figure.add_subplot(3, 1, 1)
axes2 = self.figure.add_subplot(3, 1, 2)
axes3 = self.figure.add_subplot(3, 1, 3)
axes1.yaxis.set_ticks([5,6])
axes1.set_yticklabels([5,6])
#axes.yaxis.set_offset_position('right')
axes1.yaxis.set_tick_params(color='red',labelcolor='red',direction='in',labelright = 'on',labelleft='off')
axes1.plot(np.linspace(0,10,10), np.linspace(0,10,10))
axes2.plot(np.linspace(0,10,10), np.linspace(0,10,10))
axes3.plot(np.linspace(0,10,10), np.linspace(0,10,10))
axes1.spines['bottom'].set_color('red')
axes2.spines['top'].set_color('red')
self.canvas.draw()
self.setScene(self.scene)
self.scene.addWidget(self.canvas)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setGeometry(150, 150, 1424, 750) #the first two arguments control where the window will appear on the screen, the next
self.view = View()
self.view.setGeometry(0,0,1400,700)
self.setCentralWidget(self.view)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
Other details which might be relevant: I saved the code as a .py file and I run it from the 'Anaconda Prompt' command line.
If I don't connect the mouse click event to anything, then it doesn't crash, so I can't understand why it crashes I when I use the mouse's wheel (even if not connected to anything).
You are using PyQt5 but then you import the matplotlib backend for PyQt4, so I guess this is where the error comes from.
Qt4 had a delta attribute in the class QWheelEvent but now in Qt5 this has been replaced by two different properties angleDelta and pixelDelta so that's why you get the error.
To solve it simply replace your import as follows (replace the 4 for a 5):
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
References
https://doc-snapshots.qt.io/qt5-dev/qwheelevent.html

How to integrate matplotlib fumction with QGraphicView?

I am developing a Desktop application using Qt Designer and PyQt4. I need to display a some figure with contour which in python could be done with matplotlib.pyplot.contourf. I want to display the result inside a QGraphicView object.
I am trying to do it by promoting the QGraphicView to a pygtgraph in Qt-Designer. If object name of QGraphicView is CNOPlot I have written
import matplotlib.pyplot as plt
self.CNOPlot.plot(plt.contourf(xx, yy, Z,cmap=plt.cm.autumn, alpha=0.8))
It is giving output in separate window.
I want this is to be ploted inside CNOPlot.
Here is a short example:
import matplotlib.pyplot as plt
from PyQt4 import QtGui
from PyQt4.Qt import Qt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
class MyView(QtGui.QGraphicsView):
def __init__(self):
QtGui.QGraphicsView.__init__(self)
scene = QtGui.QGraphicsScene(self)
self.scene = scene
figure = Figure()
axes = figure.gca()
axes.set_title("title")
axes.plot(plt.contourf(xx, yy, Z,cmap=plt.cm.autumn, alpha=0.8))
canvas = FigureCanvas(figure)
canvas.setGeometry(0, 0, 500, 500)
scene.addWidget(canvas)
self.setScene(scene)

matplotlib and pyqt4 transparent background [duplicate]

I am working with the matplotlib library and PyQt5 with Python 3.6. I add a figure in a window I create, and I wish to set transparent the background of this figure because I add an image to the background of the window. But, the figure is not really transparent, it duplicates the background image of the window.
For example, someone deals with the same problem two years ago :
matplotlib and pyqt4 transparent background
Here is a working example (with a background which is black but the figure is not black) :
import sys, os
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import matplotlib
matplotlib.use('Qt5Agg') # Make sure that we are using QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class SecondWindow(QWidget):
def __init__(self, parent=None):
super(SecondWindow, self).__init__(parent)
self.setupUi(self)
def setupUi(self, Form):
# WINDOW SETTINGS
Form.setWindowTitle('Hello')
self.p = QPalette()
self.pixmap = QPixmap(os.getcwd() + "/logo.png").scaled(self.size(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
self.p.setBrush(QPalette.Background, QBrush(self.pixmap))
self.setPalette(self.p)
# CREATE FIGURE AND SETTINGS
self.figure = plt.figure()
self.figure.patch.set_facecolor('None')
self.figure.patch.set_alpha(0)
self.canvas = FigureCanvas(self.figure)
self.axes = self.figure.add_subplot(111)
# WINDOW LAYOUT (with H1 and H2)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.canvas,1)
self.layout().setContentsMargins(50, 50, 50, 50)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = SecondWindow()
form.show()
sys.exit(app.exec_())
I search for answer during long hours but didn't find a solution yet. Thanks for any help you can bring !
Operating System: Windows 7 Pro
Matplotlib Version: 2.0.2 (installed via Anaconda, conda install matplotlib --channel conda-forge)
Python Version: Python 3.6
Anaconda 3
The problem occurs because the background image is set as a palette to the widget. This causes the canvas to inherit the palette and hence the canvas will also have the image as background, somehow overlaying the widget's background.
A solution would be to set the background of the canvas transparent. An easy way to do so are style sheets.
self.canvas.setStyleSheet("background-color:transparent;")
Note that this is not the same as setting the patches' facecolor to none. The figure has a background, which is controlled inside matplotlib, but the canvas, being a PyQt object also has a background.
Complete example:
import sys, os
from PyQt4.QtCore import Qt
from PyQt4.QtGui import *
import matplotlib
matplotlib.use('Qt4Agg')
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
plt.rcParams['xtick.color'] ="w"
plt.rcParams['ytick.color'] ="w"
plt.rcParams['font.size'] = 14
class SecondWindow(QWidget):
def __init__(self, parent=None):
super(SecondWindow, self).__init__(parent)
# CREATE FIGURE AND SETTINGS
self.figure = plt.figure()
self.figure.patch.set_facecolor("None")
self.canvas = FigureCanvas(self.figure)
self.axes = self.figure.add_subplot(111)
self.axes.patch.set_alpha(0.5)
###### Make the background of the canvas transparent
self.canvas.setStyleSheet("background-color:transparent;")
self.p = QPalette()
self.p.setBrush(QPalette.Background, QBrush(QPixmap("house.png")))
self.setPalette(self.p)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.canvas,1)
self.layout().setContentsMargins(50, 50, 50, 50)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = SecondWindow()
form.show()
sys.exit(app.exec_())
which might then look like

Categories

Resources