利用python开发界面 PyQt5(一) ---- 安装与简单使用

利用python开发界面 PyQt5(一) ---- 安装与简单使用


前言:
  • 利用python开发界面其实有较多工具包,个人只学习过 tkinter,但是操作比较复杂,所以个人不建议
  • 在之后偶然间接触到了PyQt5,觉得挺好用的,所以个人强烈建议使用 PyQt5
  • 话不多说,直接开始讨论,欢迎留言指正

步骤
  • 首先安装:
pip install PyQt5
- tips:在下载过程中,如果大小为49M左右,那么在pycharm中可能会出现无法联想代码,正常大小大约94M
  • 安装工具包:
pip install PyQt5-tools
- tips: 再设计界面时,使用QTDesigner会更加简单,类似于C#设计界面,只需拖拽控件
  • 添加QTDesigner 到 Pycharm -> settings -> Tools -> External Tools

安装界面

- 在安装的位置找到pyqt5designer.exe 填入Program
- 剩余的都填写 $FileDir$
- 然后就可以从pycharm任务栏 Tools -> External Tools 找到你刚才添加的应用
- 接下来就是设计界面,这里直接略过
  • 在设计完界面之后,即可通过指令生成对应文件
pyuic5 -o MainWindow.py MyQt.ui
接下来就是编写文件调用界面和将程序与界面链接
  • 话不多说,上代码, 由于在这里我是拿写给客户的界面做案例,在使用的时候建议按照自己的意愿修改部分
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/12/7/007 9:45
# @Author  : wuda
# @FileName: run.py
# @Software: PyCharm

import os
import sys
import ctypes
import inspect
import threading
from PyQt5.QtWidgets import QMainWindow, QApplication, QHeaderView, QButtonGroup, QMessageBox
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import QDateTime
from WinSoccer import WinSoccerSpider
from Main_Window import Ui_mainWindow

GAME_LIST = []


class Supervise_Main(QMainWindow, Ui_mainWindow):

    def __init__(self, parent=None):
        super(Supervise_Main, self).__init__(parent)
        self.game_name = ''
        self.gane_time = ''
        self.count = 0
        self.setupUi(self)
        self.init_ui()

    def init_ui(self):
        
        # 初始化后天运行程序
        self.hk = WinSoccerSpider(self)
        # 将后台程序发射的信号连接到对应槽函数
        self.hk.logsignal.connect(self.show_log)
        self.hk.ressignal.connect(self.show_res)
        self.hk.wrong.connect(self.wrong)
        
        # 设置对应事件触发的槽函数
        self.pushButton.clicked.connect(self.run_hk)
        self.pushButton_2.clicked.connect(self.restart)
        self.pushButton_3.clicked.connect(self.show_game)
        
        # 由于使用到了单选框,为了实现互斥,将两个radio添加到一个QButtonGroup
        self.button_group = QButtonGroup()
        self.button_group.addButton(self.radioButton)
        self.button_group.addButton(self.radioButton_2)
        self.radioButton.setChecked(True)
        # self.comboBox.setEnabled(False)
        # self.comboBox_2.setEnabled(False)

    def show_game(self):
        index = 0
        res_dict = {
            0: GAME_LIST[:200],
            1: GAME_LIST[200:400],
            2: GAME_LIST[400:600],
            3: GAME_LIST[600:]
        }
        while index < 4:
            res = QMessageBox.critical(
                self,
                '联赛名称列表',
                ', '.join(res_dict[index]),
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes
            )
            index += 1
            if res == 16384:
                continue
            else:
                break

    def run_hk(self):
        self.label_5.setText('<html><head/><body><p align="center">{0}</p></body></html>'.format('程序开始运行'))
        gameName = self.lineEdit.text()
        if gameName and gameName.strip() in GAME_LIST:
            if self.radioButton.isChecked():
                gameTime = self.comboBox.currentText()
            else:
                self.comboBox_2.setEnabled(True)
                self.comboBox.setEnabled(False)
                gameTime = self.comboBox_2.currentText()
            self.game_name = gameName
            self.gane_time = gameTime
        else:
            # 错误弹窗提示
            QMessageBox.critical(
                self,
                '联赛名称输入错误',
                '联赛名称输入错误:\n请点击查看,确保联赛名称输入正确',
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes
            )
            return
        dir_path = os.getcwd() + '\{0} {1}'.format(self.game_name, self.gane_time)
        self.label_6.setText('<html><head/><body><p><span style=" font-size:8pt;">保存地址:{0}</span></p></body></html>'.format(dir_path))
        self.thread_1 = threading.Thread(target=self.hk.start_task, args=[self.game_name, self.gane_time])
        self.thread_1.start()

    def show_log(self, value):
        self.textEdit.append(value)

    def show_res(self, value):
        self.textEdit_2.append(value)
        self.count += 1
        self.lcdNumber.display(self.count)

    def wrong(self, value):
        self.label_5.clear()
        self.label_5.setText('<html><head/><body><p align="center">{0}</p></body></html>'.format(value))

    def closeEvent(self, event):
        # 重写窗口关闭事件
        sys.exit(app.exec_())

    def restart(self):
        try:
            if self.thread_1.isAlive():
                self._async_raise(self.thread_1.ident, SystemExit)
                self.thread_1 = threading.Thread(target=self.hk.start_task, args=[self.game_name, self.gane_time])
                self.thread_1.start()
        except:
            pass

    def _async_raise(self, tid, exctype):
        # 阻塞线程,这也是我在网上找到了,当时不记得链接了,感谢作者
        """raises the exception, performs cleanup if needed"""
        tid = ctypes.c_long(tid)
        if not inspect.isclass(exctype):
            exctype = type(exctype)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            # """if it returns a number greater than one, you're in trouble,
            # and you should call it again with exc=NULL to revert the effect"""
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")
        return


if __name__ == '__main__':
    # 实例化
    app = QApplication(sys.argv)
    supervise = Supervise_Main()
    supervise.show()
    sys.exit(app.exec_())

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值