foreword
This article shares with you how to make a small desktop application with PyQt5
Overview of PyQt
PyQt5 is the Python language implementation of the Qt framework, developed by Riverbank Computing, and is one of the most powerful GUI libraries. PyQt provides a well-designed collection of window controls, and each PyQt control corresponds to a Qt control, so the API interface of PyQt is very close to that of Qt, but PyQt no longer uses the QMake system and Q_OBJECT macro.
PyQt5 can do these desktop programs.
Prepared a collection of 15 small desktop applications written in Python, which need to be obtained by leaving a message in the comment area
development tools
**Python version: **3.7
Related modules:
socket module
time module
sys module
threading module
PyQt5 module
Environment build
Install Python and add it to the environment variable, and pip installs the required related modules.
Conda environment
It is recommended to install the anaconda integrated environment, referred to as the conda environment, and the data analysis (Numpy/Pandas), crawler Scrapy framework, Web framework, PyQt and other related tools are installed by default.
installation manual
drwxr-xr-x 3 apple staff 96 2 25 2019 Anaconda-Navigator.app
drwxr-xr-x 449 apple staff 14368 10 10 18:48 bin
drwxr-xr-x 269 apple staff 8608 2 25 2019 conda-meta
drwxr-xr-x 3 apple staff 96 2 25 2019 doc
drwxr-xr-x 9 apple staff 288 11 26 14:40 envs
drwxr-xr-x 6 apple staff 192 2 25 2019 etc
drwxr-xr-x 305 apple staff 9760 5 17 2019 include
drwxr-xr-x 732 apple staff 23424 2 25 2019 lib
drwxr-xr-x 5 apple staff 160 2 25 2019 libexec
drwxr-xr-x 3 apple staff 96 2 25 2019 man
drwxr-xr-x 68 apple staff 2176 2 25 2019 mkspecs
-rw-rw-r-- 1 apple staff 745 2 25 2019 org.freedesktop.dbus-session.plist
drwxr-xr-x 15 apple staff 480 2 25 2019 phrasebooks
drwxr-xr-x 1086 apple staff 34752 9 29 18:05 pkgs
drwxr-xr-x 25 apple staff 800 2 25 2019 plugins
drwxr-xr-x 3 apple staff 96 2 25 2019 python.app
drwxr-xr-x 27 apple staff 864 2 25 2019 qml
drwxr-xr-x 7 apple staff 224 2 25 2019 resources
drwxr-xr-x 14 apple staff 448 2 25 2019 sbin
drwxr-xr-x 25 apple staff 800 2 25 2019 share
drwxr-xr-x 9 apple staff 288 2 25 2019 ssl
drwxr-xr-x 290 apple staff 9280 2 25 2019 translations
In the bin directory, there is a Designer.app application that is PyQt's Designer designer. The file extension is .ui.
Because after Conda is installed, the default is the base environment, so you can use the Coda command to create a new development environment:
conda create -n gui python=python3.7
Activate the environment
conda activate gui
Install pyqt5
(gui) > pip install pyqt5==5.10
If the installed PyQt5 version is higher than 5.10, some libraries will be installed separately, such as WebEngine
(gui) > pip install PyQtWebEngine
PyQt5+Socket realizes centralized network service
Server side (full code)
import json
import socket
import threading
import time
from data import DataSource
class ClientThread(threading.Thread):
def __init__(self, client, addr):
super(ClientThread, self).__init__()
self.client = client
self.addr = addr
self.login_user = None
print('{} 连接成功!'.format(addr))
self.client.send(b'OK 200')
def run(self) -> None:
while True:
b_msg = self.client.recv(1024*8) # 等待接收客户端信息
if b_msg == b'exit':
break
# 解析命令
try:
self.parse_cmd(b_msg.decode('utf-8'))
except:
self.client.send(b'Error')
self.client.send(b'closing')
print('{} 断开连接'.format(self.addr))
def parse_cmd(self, cmd):
print('接收命令-----', cmd)
if cmd.startswith('login'):
# login username pwd
_, name, pwd = cmd.split()
for item in datas:
if item['name'] == name and item['pwd'] == pwd:
self.login_user = item
if self.login_user is not None:
self.client.send(b'OK 200')
else:
self.client.send(b'not exist user')
else:
if self.login_user is None:
self.client.send(b'no login session')
elif cmd.startswith('add'):
# add 100
blance = float(cmd.split()[-1])
self.login_user['blance'] += blance
self.client.send(b'OK 200')
elif cmd.startswith('sub'):
# sub 100
blance = float(cmd.split()[-1])
self.login_user['blance'] -= blance
self.client.send(b'OK 200')
elif cmd.startswith('get'):
self.client.send(json.dumps(self.login_user, ensure_ascii=False).encode('utf-8'))
if __name__ == '__main__':
datas = DataSource().load()
# 创建socket应用服务
server = socket.socket()
server.bind(('localhost', 18900)) # 绑定主机IP和Host
server.listen()
print('中心服务已启动\n等待客户端连接...')
while True:
client, addr = server.accept()
ClientThread(client, addr).start()
time.sleep(0.5)
Client (full code)
import socket
import threading
class CenterClient():
def __init__(self, server, port):
super().__init__()
self.server = server
self.port = port
self.isConnected = False
self.client = None
def connect(self):
self.client = socket.socket()
self.client.connect((self.server, self.port))
msg = self.client.recv(8*1024)
if msg == b'OK 200':
print('---连接成功--')
self.isConnected = True
else:
print('---连接失败---')
self.isConnected = False
def send_cmd(self, cmd):
self.client.send(cmd.encode('utf-8'))
data = self.client.recv(8*1024)
print('{}命令结果: {}'.format(cmd, data))
if data == b'Error':
return '400'
return data.decode('utf-8')
if __name__ == '__main__':
client = CenterClient('localhost', 18900)
client.connect()
print(client.send_cmd('login disen disen123'))
# print(client.send_cmd('add 1000'))
# print(client.send_cmd('sub 50'))
print(client.send_cmd('get'))
at last
In order to thank the readers, I would like to share with you some of my recent favorite programming dry goods, to give back to every reader, and hope to help you.
There is a full set of information suitable for beginners~
Come and grow up with Xiaoyu!
① More than 100+ Python e-books (mainstream and classic books should be available)
② Python standard library information (the most complete Chinese version)
③ Source code of reptile projects (forty or fifty interesting and classic hand-practicing projects and source codes)
④ Videos on basics of Python, crawlers, web development, and big data analysis (suitable for beginners)
⑤ Python Learning Roadmap (Farewell to Influential Learning)