How to Develop Python Desktop Applications with PyQt5: Installation, UI Design, Image Processing, Remote Control, and Packaging
This tutorial explains step‑by‑step how to install PyQt5, create and customize GUI windows, integrate Qt Designer, embed web pages, process images with OpenCV, implement remote desktop control via Flask and pyautogui, and finally package the Python application into a standalone executable.
Installing PyQt5 and Related Tools
Use pip install PyQt5 (optionally with a mirror) and then install pip install pyqt5-tools to obtain Qt Designer. Verify the installation by running pyuic5 which should output an error indicating successful setup.
Creating a Simple Widget Application
In PyCharm, write a minimal script that imports sys and QApplication, QWidget from PyQt5.QtWidgets , creates a QWidget , sets its size, position, title, and shows it before entering the event loop.
<code>import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = QWidget()
widget.resize(400, 200)
widget.move(300, 300)
widget.setWindowTitle("First PyQt5 Desktop App")
widget.show()
sys.exit(app.exec_())
</code>Adding Qt Designer Support in PyCharm
Configure an external tool named "Qt Designer" pointing to the designer.exe path, set the working directory to $ProjectFileDir$ , and then convert .ui files to Python modules with pyuic5 -o xxx.py xxx.ui .
Loading a .ui File in the Main Program
Import the generated Python UI module and instantiate it inside the main window:
<code>import sys
from PyQt5.QtWidgets import QApplication, QWidget
import English
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = QWidget()
ui = English.Ui_Form()
ui.setupUi(widget)
widget.show()
sys.exit(app.exec_())
</code>Creating a Custom QWidget Subclass
Subclass QWidget to set a window icon, geometry, and title, then launch it in the usual way.
<code>import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget
class UsingTest(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle("Wake Wrist")
self.setGeometry(300, 300, 350, 150)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = UsingTest()
win.setWindowIcon(QIcon("./excel_wrist.ico"))
win.show()
sys.exit(app.exec_())
</code>Displaying Images in a MainWindow
Generate a UI with a QLabel for the image and a button, then load a picture with QPixmap and display it.
Image Processing with OpenCV
Combine PyQt5, NumPy, and OpenCV to open, blur, and display images. The GUI provides Open, Save, Process, and Quit buttons, and the processing slot applies cv2.blur(img, (5,5)) .
<code>import sys, cv2, numpy as np
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QDialog, QFileDialog, QGridLayout, QLabel, QPushButton
class Window(QDialog):
def __init__(self):
super().__init__()
self.img = np.ndarray(())
self.initUI()
# UI setup omitted for brevity
def openSlot(self):
fileName, _ = QFileDialog.getOpenFileName(self, 'Open Image', '', '*.png *.jpg *.bmp')
self.img = cv2.imread(fileName, -1)
self.refreshShow()
def processSlot(self):
self.img = cv2.blur(self.img, (5,5))
self.refreshShow()
def refreshShow(self):
h, w, c = self.img.shape
bytesPerLine = 3 * w
qImg = QImage(self.img.data, w, h, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
self.label.setPixmap(QPixmap.fromImage(qImg).scaledToHeight(400))
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
</code>Remote Desktop Control with Flask, pyautogui and a Web Front‑end
Serve a live screenshot stream via Flask, capture mouse click coordinates on a web page using jQuery, convert the percentages to screen coordinates, and invoke pyautogui.click(x, y) on the server.
<code>import pyautogui, io
from flask import Flask, render_template, Response, request
import pyautogui
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/pointer')
def pointer():
x = int(float(request.args['xrate']) * 1920)
y = int(float(request.args['yrate']) * 1080)
pyautogui.click(x, y)
return 'success'
def gen():
while True:
img = pyautogui.screenshot()
buf = io.BytesIO()
img.save(buf, format='JPEG')
frame = buf.getvalue()
yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame)
@app.route('/video_feed')
def video_feed():
return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, threaded=True)
</code>Embedding the Web Page in a PyQt5 GUI
Install PyQtWebEngine and load the remote URL inside a QWebEngineView widget.
<code>pip install PyQtWebEngine
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget
class UsingTest(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Wake Wrist')
self.setFixedSize(1500, 900)
self.browser = QWebEngineView()
self.browser.load(QUrl('http://wrist.cc/'))
self.setCentralWidget(self.browser)
def setCenterPosition(self):
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = UsingTest()
win.setWindowIcon(QIcon('./excel_wrist.ico'))
win.setCenterPosition()
win.show()
sys.exit(app.exec_())
</code>Packaging the Application into an Executable
Install pyinstaller and run pyinstaller -F your_script.py (or -D for a folder). Common options include -w to hide the console, -i to set an icon, and -p to add search paths.
Handling Executable Crash Issues
If the packaged exe closes instantly, run it from a command prompt to view error messages. For multi‑file projects, generate a .spec file with pyi-makespec main.py , add all modules and data files to the Analysis list, then build with pyinstaller -D main.spec .
Overall, the guide walks through the complete workflow from environment setup, UI creation, advanced features such as image processing and remote control, to final distribution as a standalone Windows executable.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.