Python实战案例,PyQt5+socket模块,Python制作小型桌面应用

前言

本文给大家分享的是如何通过用PyQt5制作小型桌面应用

PyQt概述

PyQt5是Qt框架的Python语言实现,由Riverbank Computing开发,是最强大的GUI库之一。PyQt提供了一个设计良好的窗口控件集合,每一个PyQt控件都对应一个Qt控件,因此PyQt的API接口与Qt的API接口很接近,但PyQt不再使用QMake系统和Q_OBJECT宏。

PyQt5可以做这些桌面程序。

准备了Python 编写的 15 个小型桌面应用程序的合集,需要评论区留言获取

在这里插入图片描述

开发工具

**Python版本:**3.7

相关模块:

socket模块

time模块

sys模块

threading模块

PyQt5模块

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

Conda环境

建议安装anaconda集成环境,简称conda环境, 内部默认安装数据分析(Numpy/Pandas)、爬虫Scrapy框架、Web框架、PyQt等相关工具。

安装目录

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

在 bin目录下,存在一个Designer.app应用是PyQt的Designer设计器。文件的扩展名是.ui。
因为Conda安装之后,默认是base环境,所以可以使用Coda命令创建新的开发环境:

conda create -n gui python=python3.7

激活环境

conda activate gui

安装pyqt5

(gui) > pip install pyqt5==5.10

如果安装的PyQt5版本高于5.10,部分库将要单独安装,如WebEngine

(gui) > pip install PyQtWebEngine

PyQt5+Socket实现中心化网络服务

服务器端(完整代码)

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)

客户端(完整代码)

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'))


最后

为了感谢读者们,我想把我最近收藏的一些编程干货分享给大家,回馈每一个读者,希望能帮到你们。

里面有适合小白新手的全套资料给到大家~

快来和小鱼一起成长进步吧!

① 100+多本Python电子书(主流和经典的书籍应该都有了)

② Python标准库资料(最全中文版)

③ 爬虫项目源码(四五十个有趣且经典的练手项目及源码)

④ Python基础入门、爬虫、web开发、大数据分析方面的视频(适合小白学习)

⑤ Python学习路线图(告别不入流的学习)

素材

猜你喜欢

转载自blog.csdn.net/Modeler_xiaoyu/article/details/128218504