当前位置: 首页 > 工具软件 > pyrasite-gui > 使用案例 >

Python GUI development

花飞尘
2023-12-01

Today,I will introduce some of the gadgets I made during my first year of graduate study.We all know that Python is popular these days.Python is a force in artificial intelligence.Here is a way to encapsulate your work into a software interface.I'll write the interface functions so you can deploy and develop faster.

The main work is as follows:

  • Design interface code separation framework(it is easy,unprofessional)

  • The UI interface integrate with the code

  • Exception log handling

  • Interface definition

Let's get started:

1:Installation required environment,The following environment is recommended

  • pip install pyqt5
  • pip install opencv-python
  • You can download the corresponding installation package from the QT website

  • Other libraries you need

2.UI design

  • This section designs the UI based on your personal needs

  • I'll use the example of a button to load a video and display on the software

  • Name the UI controls according to the requirements(it needs to use the English)

3.Compiling UI files

  • You can use this code“pyuic5 yourUI.ui -o yourUI.py”In the CMD terminal,Compile the qt designed UI file into a python usable file

4.Use a design framework

  • Import the required python libraries,You can refer to the following code
#======================================
# 只要修改界面布局等均要执行该段代码
#======================================
#pyuic5 FormUI.ui -o FormUI.py
#======================================
# -*- coding: utf-8 -*-
#--------------------------------------
from FormUI import Ui_Dialog#导入UI文件
#--------------------------------------
#--------------------------------------
from PyQt5 import QtCore, QtGui,QtWidgets
from PyQt5.QtGui import QIcon,QPalette,QBrush,QPixmap
from PyQt5.QtWidgets import QFileDialog#文件操作
from PyQt5.QtCore import QTimer
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
#--------------------------------------
  • Import the log file,You can refer to the following code
from your_logging import Logger
# 日志
log = Logger('your.py')
logger = log.getlog()
  • Load frame code,You can refer to the following code
#------------------------------------------------------------
#实现界面与代码的分离
#------------------------------------------------------------
class MyMaster(QtWidgets.QWidget,Ui_Dialog):   
    def __init__(self):
        #--------------------------------------
        super(MyMaster,self).__init__()#构造器方法返回父级的对象
        self.setupUi(self)
        #--------------------------------------
        #other your code
#--------------------------------------
# 主运行程序
#--------------------------------------
if __name__=="__main__":  
    app = QtWidgets.QApplication(sys.argv)  
    MyMasterShow = MyMaster()
    MyMasterShow.show()
    sys.exit(app.exec_()) 
  • How do I use log files,You can refer to the following code
        try:
            #code
            # 日志
            logger.info("your needs")
        except Exception as ee:
            logger.error(ee)
  • The association of code with the interface,You can refer to the following code

#=========================================================================================
        # 下面的程序主要是控件的槽函数绑定
        self.Button_OpenVideo.clicked.connect(self.Button_OpenVideo_clicked)
        self.Button_pose.clicked.connect(self.Button_pose_clicked)
        self.Button_action.clicked.connect(self.Button_action_clicked)
       #=========================================================================================
  • The position of the associated function,You can refer to the following code
#------------------------------------------------------------
#实现界面与代码的分离
#------------------------------------------------------------
class MyMaster(QtWidgets.QWidget,Ui_Dialog):   
    def __init__(self):
        #--------------------------------------
        super(MyMaster,self).__init__()#构造器方法返回父级的对象
        self.setupUi(self)
        #--------------------------------------
        self.setWindowTitle('WindowTitle')
        self.setWindowIcon(QIcon('logo.ico'))
        #--------------------------------------
        #--------------------------------------
        #=========================================================================================
        # 下面的程序主要是控件的槽函数绑定
        self.Button_OpenVideo.clicked.connect(self.Button_OpenVideo_clicked)
        self.Button_pose.clicked.connect(self.Button_pose_clicked)
        self.Button_action.clicked.connect(self.Button_action_clicked)
        #=========================================================================================
    #选择视频文件
    def Button_OpenVideo_clicked(self):
        try:
            #code
            # 日志
            logger.info("Open File--%s Success")
        except Exception as ee:
            logger.error(ee)
    def Button_pose_clicked(self):
        pass
    def Button_action_clicked(self):
        pass
  • Open the function of the video button,You can refer to the following code,This part of the code was debugged for a long time at that time, if the display error or image color change, the basic problem is the image format, you need to know whether the display format is consistent with your image format.you need know cvimread will Convert RGB image to BGR image.UI needs the BGR image,you can  use the function"cv2.COLOR_BGR2RGB"to convert.I suggest that you use exchange the channel of R and B,this way is useful.we know the python libraries that the output image format is RGB.and you can exchange the channel of R and B to convert BGR,now,you can use the following code to display you image.

            self.fileName,fileType = QtWidgets.QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(),\
                                "All Files(*);;MP4 Files(*.mp4);;AVI Files(*.avi)")
            self.cap = cv2.VideoCapture(self.fileName)
            self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
            frame = 0
            flag = True
            while(flag):
                if frame <= self.frames:
                    ret,self.frame = self.cap.read()
                    if ret:
                        #show the frame
                        ShowFrame = cv2.resize(self.frame, (640, 480))
                        ShowFrame = cv2.cvtColor(ShowFrame, cv2.COLOR_BGR2RGB)
                        ShowImage = QtGui.QImage(ShowFrame.data, ShowFrame.shape[1], ShowFrame.shape[0], QtGui.QImage.Format_RGB888)
                        self.label_show_camera_src.setPixmap(QtGui.QPixmap.fromImage(ShowImage))
                        cv2.waitKey(1)
                        frame += 1
                        # print(frame)
                    else:
                        break
                else:
                    pass
            self.cap.release()
  • log files ,You can refer to the following code
import logging
 
class Logger():
    def __init__(self, logName):
        # 创建一个logger
        self.logger = logging.getLogger(logName)
 
        # 判断,如果logger.handlers列表为空,则添加,否则,直接去写日志,试图解决日志重复
        if not self.logger.handlers:
            self.logger.setLevel(logging.INFO)
 
            # 创建一个handler,用于写入日志文件
            fh = logging.FileHandler('log.log')
            fh.setLevel(logging.INFO)
 
            # 再创建一个handler,用于输出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)
 
            # 定义handler的输出格式
            formatter = logging.Formatter('%(levelname)s:%(asctime)s -%(name)s -%(message)s')
            fh.setFormatter(formatter)
            ch.setFormatter(formatter)
 
            # 给logger添加handler处理器
            self.logger.addHandler(fh)
            self.logger.addHandler(ch)
 
    def getlog(self):
        return self.logger
  • The words written in the back.you need know the "self" .If you need to use other slot function of  variable.you can use the rule:self.variable = your variable.Now,You can useself.variable in other functions.Writing English blog for the first time, grammar and other problems are inevitable, please ignore.
 类似资料:

相关阅读

相关文章

相关问答