Python GUI development

51 篇文章 2 订阅
16 篇文章 1 订阅

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.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Develop more dynamic and robust GUI applications using PySide, an open source cross-platform UI framework About This Book Designed for beginners to help you get started with GUI application development Develop your own applications by creating customized widgets and dialogs Written in a simple and elegant structure so you easily understand how to program various GUI components Who This Book Is For This book is written for Python programmers who want to learn about GUI programming. It is also suitable for those who are new to Python but are familiar with object-oriented programming. What You Will Learn Program GUI applications in an easy and efficient way Download and install PySide, a cross-platform GUI development toolkit for Python Create menus, toolbars, status bars, and child windows Develop a text editor application on your own Connect your GUI to a database and manage it Execute SQL queries by handling databases In Detail Elegantly-built GUI applications are always a massive hit among users. PySide is an open source software project that provides Python bindings for the Qt cross-platform UI framework. Combining the power of Qt and Python, PySide provides easy access to the Qt framework for Python developers and also acts as an excellent rapid application development platform. This book will take you through everything you need to know to develop UI applications. You will learn about installing and building PySide in various major operating systems as well as the basics of GUI programming. The book will then move on to discuss event management, signals and slots, and the widgets and dialogs available with PySide. Database interaction and manipulation is also covered. By the end of this book, you will be able to program GUI applications efficiently and master how to develop your own applications and how to run them across platforms. Style and approach This is an accessible and practical guide to developing GUIs for Python applications. Table of Contents Chapter 1: Getting Started with PySide Chapter 2: Entering through Windows Chapter 3: Main Windows and Layout Management Chapter 4: Events and Signals Chapter 5: Dialogs and Widgets Chapter 6: Database Handling
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值