I'm just starting out writing a program with the PyQt5 gui framework. I have a file, resource_loader.py, which is responsible for loading images etc.
The problem
Python crashes at the line where the image is loaded. I'm using IDLE (3.5) and after I run the program there is no output except for:
=============================== RESTART: Shell ===============================
Code - pretty much copy/pasted from a tutorial, file is called resource_loader.py
from PyQt5 import QtGui
import os
file_image = QtGui.QPixmap("file.png")
Things I've tried
file.png definitely is in the same directory as resource_loader.py
Changing up the variable names, just in case.
Moving the file to a location with no spaces in the path
Extra information
I am running resource_loader.py directly
I am using Linux Mint (18.3) Xfce if that's any use.
Thanks in advance.
It is required to place your code within a QApplication instance as follows:
import sys
import os
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QWidget)
app = QApplication(sys.argv)
file_image = QtGui.QPixmap("file.png")
sys.exit(app.exec_())
Related
I have a python code that I wrote, I want to run this code on other computers, and those computers do not have python installed, nor do they have library that I use in the script.
For example script.py
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
import sys
def main():
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(200,200,300,300)
win.setWindowTitle("My first window!")
label = QLabel(win)
label.setText("my first label")
label.move(50, 50)
win.show()
sys.exit(app.exec_())
main() # make sure to call the function
My solution was to convert my script to an exe file with pyinstaller, but when I try to run the exe file on other computers, it didn't work there.
pyinstaller --onefile -w script.py
script.exe file works for my computer, but on another computer that doesn't have python it doesn't work, and also I cant install PyQt5 library on other computers.
Is there a way to run a python script on computers without python installed?
I keep getting errors when I use python installers (my primary installer contains various libraries such as QSci and other libraries that are part of PyQt5). For example, when I try to convert a simple project with the code below to an executable, it errors out saying ModuleNotFoundError: No module named 'PyQt5.QtPrintSupport'. The projects do compile and run well though. I wonder what is wrong? Thank you in advance!
import sys
import os
import PyQt5
from PyQt5 import QtWidgets, Qsci
from PyQt5 import QtPrintSupport
app = QtWidgets.QApplication(sys.argv)
editor = Qsci.QsciScintilla()
lexer = Qsci.QsciLexerPython(editor)
editor.setLexer(lexer)
## setup autocompletion
api = Qsci.QsciAPIs(lexer)
# import the desired api file
pyqt_path = os.path.dirname(PyQt5.__file__)
api.load(os.path.join(pyqt_path, "Qt/qsci/api/python/Python-3.6.api"))
api.prepare()
editor.setAutoCompletionThreshold(1)
editor.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll)
editor.show()
editor.setText(open(sys.argv[0]).read())
sys.exit(app.exec_())
I recently cloned a github repository (https://github.com/lpbsscientist/YeaZ-GUI.git) to begin understanding the code and making edits to it. I have set up a conda virtual environment with all the dependencies required and have been running GUI_main.py successfully via the command line.
In an attempt to gain a better understanding of what the script does, I opened it in Atom and began making edits (not saving them). I inserted several print statements and additional comments. With the path to the virtual environment saved as profile on the Atom script package, I was able to successfully run GUI_main.py from Atom.
So far, so good.
I then saved the current version of GUI_main.py. I tried to run it again, but this time, I got the following error:
File "GUI_main.py", line 55, in <module> import neural_network as nn ModuleNotFoundError: No module named 'neural_network
I got the same error message running the new saved version of GUI_main.py from the command line, atom, and the python 3.6.8 IDE.
I have made no edits to the file structure in GitHub repo. GUI_main.py is located in the directory YeaZ-GUI. This script imports several modules in the subdirectory YeaZ-GUI/unet, and the script appends their paths correctly (as far as I know - see initialization commands below). GUI_main.py imports numerous modules in the following important statement:
#!/usr/bin/env python3
import sys
import numpy as np
import pandas as pd
import h5py
import skimage
# For writing excel files
#from openpyxl import load_workbook
#from openpyxl import Workbook
# Import everything for the Graphical User Interface from the PyQt5 library.
from PyQt5.QtWidgets import (QApplication, QMainWindow, QDialog, QSpinBox,
QMessageBox, QPushButton, QCheckBox, QAction, QStatusBar, QLabel)
from PyQt5 import QtGui
#Import from matplotlib to use it to display the pictures and masks.
from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from sklearn.decomposition import PCA
import imageio
from PIL import Image, ImageDraw
#append all the paths where the modules are stored. Such that this script
#looks into all of these folders when importing modules.
sys.path.append("./unet")
sys.path.append("./disk")
sys.path.append("./icons")
sys.path.append("./init")
sys.path.append("./misc")
from PlotCanvas import PlotCanvas
import Extract as extr
from image_loader import load_image
from segment import segment
import neural_network as nn #this is the statement causing the error
Curious as to what was going on, I deleted the current version of GUI_main.py and redownloaded the GUI_main.py script from the Github repo mentioned above and placed it into the same location it was before.
This time, I made the same edits via the python IDE, and I was then able to successfully run the script from the command line with no errors.
However, After opening this edited version of the file in Atom and saving it (making no edits), I got the exact same error message as before - after running from Atom as well as the command line.
Interestingly, repeating this same procedure for the neural_network.py module as well as other modules (i.e editing it, saving it in Atom, and then running it) gives no error message.
It seems like the problem is resulting from the action of saving GUI_main.py on Atom? Could this be possible? Please offer any insight.
So, I did some more experimenting. Turns out that I had downloaded an auto-formatting package (auto pep8) through Atom that was changing the order of my import statements upon saving.
The package's auto-formating moved the import neural_networks as nn to a position before the sys.path.append statements and thus the subdirectory unet where neural_network.py is located was not being searched for importable modules.
I have PyQt5 Installed and I created a GUI and edited it using Sublime Text, Now I want to use PyCharm and I saw posts that you don't have to configure PyQt5, it is automatically detected by PyCharm.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
from mainpy import kitcode
PyQt5, QtCore, QtGui, QtWidgets, PyQt5.QtWidgets, PyQt5.QtGui, QPixmap, mainpy and kitcode are all in red underline.
And when I run it, I get the error
Traceback (most recent call last):
File "C:/Users/username/Desktop/folder/PythonThesis/mainpy.py", line 9, in <module>
from PyQt5 import QtCore, QtGui, QtWidgets
ImportError: No module named 'PyQt5'
Process finished with exit code 1
any help would be appreciated and sorry if this is basic, I am still new to python. Thank you very much.
did you fix this problem?
You may need to tell PyCharm which Python do you want to use for your current project. You can do this by configuring Python interpreter from Settings/Preferences/Project Interpreter. Be careful to find the proper Python with PyQt5. You can find more information on the official website. An extra tip is you can edit run configuration, including Python interpreter for the next run, before running projects by using the shortcut Shift+Alt+F10.
my python application looks like:
test.py
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtSql
import sys
import atexit
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
db = QtSql.QSqlDatabase.addDatabase('QODBC')
sys.exit(app.exec_())
If i run this application, everything works fine. However, if I create an executable with cx_freeze, I always get the following error:
QSqlDatabase: QODBC driver not loaded
QSqlDatabase: available drivers:
I use the following command to create the executable:
C:\Python27\Scripts\cxfreeze.bat test.py --target-dir C:\Test --include-path="C:\Python27\Lib\site-packages\PyQt4"
If I look into C:\Test (the location where cx_freeze created the executable), I see a bunch of *.dll files with the word 'sql' in it (qsqlodbc4.dll, QtSql4.dll...)
In the past, I created a few PyQT applications with cx_freeze and it always worked really well. However together with the QtSql module, I always get the error message above.
My operating system: Windows 7
Do you guys have any ideas on how to resolve the problem?
edit: Okay, I got it. I copied the contents of PyQt4\plugins\sqldrivers to C:\Test\sqldrivers and now it works.
Kind Regards
Bernhard
This woks only in your developer machine, but when you create a exe file and run this file in other machine it didn't work.
I use pyinstaller, and solve the problem.
only use:
pyinstaller --onefile --windowed myscript.py