IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> pyqt5做了一个无线网连接器,与君共勉 -> 正文阅读

[Python知识库]pyqt5做了一个无线网连接器,与君共勉

作者:recommend-item-box type_blog clearfix

最近打开电脑wifi连接老是出现各种问题,于是突发奇想,我自己能不能做一个wifi连接的小工具岂不是就没有这些麻烦了,居然成功了。

为了方便不会python的朋友也能够使用,于是我用pyqt5将其做成了界面化的小工具,希望可以帮助到和我有一样困惑的小伙伴。

另外,也可以帮助大家了解到pyqt5 ui的使用过程,最后我将wifi连接小工具打包成了exe的应用程序,大家可以直接下载使用。

1、准备

准备工作就是介绍一下使用到的第三方的非标准库,第一个使用到的就是pywifi模块,
使用这个模块来完成对wifi的控制操作。

不过在运行的过程中遇到了一个问题,就是安装好pywifi模块以后还会提示缺少comtypes,不过没有影响我们将这个库安装就好了。

pip install pywifi -i https://pypi.tuna.tsinghua.edu.cn/simple

pip install comtypes -i https://pypi.tuna.tsinghua.edu.cn/simple

安装好需要的第三方非标准库,将需要的python模块内容导入到我们的代码块中就OK了。

import time

from pywifi import const, PyWiFi, Profile

接下来就是PyQt5模块了,这个模块之前已经使用好多回了,直接使用pip的方式安装。安装好PyQt5模块后,将其导入到python代码块中。

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import sys

import traceback

2、UI应用

要制作wifi无线网连接小工具,需要先将UI界面部分写好,话不多说,我们直接创建一个class来专门编写关于UI界面的部分,开始介绍之前先来看一下我们已经写好的UI界面效果。

wifi连接器主界面.png

class WifiUI(QWidget):
    def __init__(self):
        super(WifiUI, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('wifi 连接器  来源公众号:Python 集中营')
        self.setWindowIcon(QIcon('wifi.png'))
        self.setFixedSize(500, 300)

        self.brower = QTextBrowser()
        self.brower.setFont(QFont('宋体', 8))
        self.brower.setReadOnly(True)
        self.brower.setPlaceholderText('处理进程展示区域...')
        self.brower.ensureCursorVisible()

        self.check_status_btn = QPushButton()
        self.check_status_btn.setText('检查连接状态')
        self.check_status_btn.clicked.connect(self.check_status_btn_click)

        self.wifi_list_btn = QPushButton()
        self.wifi_list_btn.setText('获取wifi列表')
        self.wifi_list_btn.clicked.connect(self.wifi_list_btn_click)

        self.wifi_ssid_in = QLineEdit()
        self.wifi_ssid_in.setPlaceholderText('wifi 名称')

        self.wifi_pwd_in = QLineEdit()
        self.wifi_pwd_in.setPlaceholderText('wifi 密码')

        self.conn_btn = QPushButton()
        self.conn_btn.setText('开始连接wifi')
        self.conn_btn.clicked.connect(self.connect_wifi)

        hbox = QHBoxLayout()
        hbox.addWidget(self.brower)
        vbox = QVBoxLayout()
        vbox.addWidget(self.check_status_btn)
        vbox.addWidget(self.wifi_list_btn)
        vbox.addWidget(self.wifi_ssid_in)
        vbox.addWidget(self.wifi_pwd_in)
        vbox.addStretch(1)
        vbox.addWidget(self.conn_btn)
        hbox.addLayout(vbox)

        self.setLayout(hbox)

        self.wifi_list_thread = WiFiThread()
        self.wifi_list_thread.message.connect(self.show_message)
        self.wifi_list_thread.finished.connect(self.finished_wifilist)

        self.wifi_conn_thread = CoonThread(self)
        self.wifi_conn_thread.message.connect(self.show_message)
        self.wifi_conn_thread.finished.connect(self.finished_conn)

    def finished_wifilist(self, finished):
        if finished is True:
            self.wifi_list_btn.setEnabled(True)
            self.wifi_list_btn.setText('获取wifi列表')

    def finished_conn(self, finished):
        if finished is True:
            self.conn_btn.setEnabled(True)
            self.conn_btn.setText('开始连接wifi')

    def show_message(self, text):
        cursor = self.brower.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.brower.append(text)
        self.brower.setTextCursor(cursor)
        self.brower.ensureCursorVisible()

    def check_status_btn_click(self):
        wifi = PyWiFi()
        interface = wifi.interfaces()[0]

        if interface.status() in [const.IFACE_CONNECTED, const.IFACE_INACTIVE]:
            self.show_message('当前计算机已连接wifi!')
        else:
            self.show_message('当前计算机未连接wifi!')

    def wifi_list_btn_click(self):
        self.wifi_list_btn.setEnabled(False)
        self.wifi_list_btn.setText('正在获取...')
        self.wifi_list_thread.start()

    def connect_wifi(self):
        self.conn_btn.setEnabled(False)
        self.conn_btn.setText('正在连接...')
        self.wifi_conn_thread.start()

3、业务线程

使用PyQt5中的QThread子线程来专门开发业务相关的代码块,实现使用名称、密码连接wifi的功能。然后将该线程加入到UI界面的主线程中单独运行即可。这里将wifi连接和扫描wifi业务分为了两个子线程来做,分别是WiFiThread、CoonThread两个线程。

class WiFiThread(QThread):
    message = pyqtSignal(str)
    finished = pyqtSignal(bool)

    def __init__(self):
        super(WiFiThread, self).__init__()
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        wifi = PyWiFi()
        interface = wifi.interfaces()[0]

        interface.scan()
        self.message.emit('正在扫描wifi列表...')
        time.sleep(3)
        wifis = interface.scan_results()
        self.message.emit('wifi列表扫描完成!')

        for i in wifis:
            self.message.emit('wifi 名称:{}'.format(i.ssid))
            self.message.emit('wifi 设备mac地址:{}'.format(i.bssid))

        self.finished.emit(True)


class CoonThread(QThread):
    message = pyqtSignal(str)
    finished = pyqtSignal(bool)

    def __init__(self, parent=None):
        super(CoonThread, self).__init__(parent)
        self.working = True
        self.parent = parent

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        try:
            wifi = PyWiFi()
            interface = wifi.interfaces()[0]

            if interface.status() == const.IFACE_CONNECTED:
                interface.disconnect()
                time.sleep(3)

            profile = Profile()  # 配置文件
            profile.ssid = self.parent.wifi_ssid_in.text().strip()  # wifi名称
            self.message.emit('wifi 名称:{}'.format(self.parent.wifi_ssid_in.text().strip()))
            profile.auth = const.AUTH_ALG_OPEN  # 需要密码
            profile.akm.append(const.AKM_TYPE_WPA2PSK)  # 加密类型
            profile.cipher = const.CIPHER_TYPE_CCMP  # 加密单元
            profile.key = self.parent.wifi_pwd_in.text().strip()  # wifi密码
            self.message.emit('wifi 密码:{}'.format(self.parent.wifi_pwd_in.text().strip()))

            interface.remove_all_network_profiles()  # 删除其它配置文件
            tmp_profile = interface.add_network_profile(profile)  # 加载配置文件
            interface.connect(tmp_profile)

            time.sleep(5)

            if interface.status() == const.IFACE_CONNECTED:
                self.message.emit('wifi名称:{}连接成功!'.format(self.parent.wifi_ssid_in.text().strip()))
            else:
                self.message.emit('wifi名称:{}连接失败!'.format(self.parent.wifi_ssid_in.text().strip()))

            time.sleep(1)
            self.finished.emit(True)
        except Exception as e:
            traceback.print_exc()
            self.message.emit('wifi 连接出现异常!')
            self.finished.emit(True)

4、主函数

最后,使用main主函数将整个应用启动即可看到整个页面应用直接使用相应的功能连接wifi。

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = WifiUI()
    main.show()
    sys.exit(app.exec_())

以上代码块部分乃是无线网连接器小工具的全部代码块,不用单独再获取源码。将文章的全部带那块挨个copy到一个.py的python文件中直接运行即可。

感谢大家的持续关注,Python 集中营会不断的分享编程相关的知识干货来回馈每位朋友!

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-08-06 10:40:12  更:2022-08-06 10:41:06 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/18 10:43:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码