Getting Started with PyQt5 3 - Add a button and read a specific image

Preface to study

Come up with a visual interface, although it may not be useful, but give it a try.
Insert image description here

PyQt5 classes used

Creating a canvas requires the use of QPushButton. QPushButton is the button class in the QT interface, which inherits from QAbstractButton.

You need to import it from QtWidgets before use:

from PyQt5.QtWidgets import QApplication, QTextBrowser, QWidget, QLabel, QPushButton

Use the following command to create a QLabel. The first parameter passed in is the text it displays.

self.btn_photo = QPushButton('获取图片', self)

QLabel has multiple methods, the more commonly used ones are the following:

1, .setText method is used to set text:

self.btn_photo.setText('获取图片')

2, .setToolTip method sets the prompt when the mouse is placed on it:

self.btn_photo.setToolTip('点击后从电脑中读取图片')

3, .move method is used to move the window:

self.btn_photo.move(10, 50)

4. .setIcon To set the icon, you need to use the QIcon class. QIcon plus the path can read the image into an icon. .setIconSize Use To set the icon size:

self.btn_photo.setIcon("QLabel{background:white;}")
self.btn_photo.setIconSize(QSize(50, 50))

5, .clicked.connectSet the trigger function after click:

self.btn_photo.clicked.connect(self.openimage)

6, .setObjectNameSet component name:

self.label_show_camera.setObjectName("image_show")

Example usage

1. Window construction

a. Build basic classes

First draw a button in the Example built in the previous step.

#-----------------------------#
#   获取图片按钮
#-----------------------------#
self.btn_photo = QPushButton('获取图片', self)
self.btn_photo.setToolTip('点击后从电脑中读取图片')
self.btn_photo.setIcon(QIcon("img/icon/Search.jpeg"))
self.btn_photo.setIconSize(QSize(50, 50))
self.btn_photo.resize(130, 60)
self.btn_photo.move(330, 50)   
self.btn_photo.clicked.connect(self.openimage)

b. openimage trigger function-read existing pictures and display them

The overall steps are as follows:

  • Prepare a picture, set the name of the picture to photo.jpg, and put it in a folder with the py file:
    Please add image description
  • Use PIL or cv2 to read images. Here we use PIL.
  • Since we specified the size of QLabel above, we need to resize the image.
#-----------------------------#
#   打开图片模式
#-----------------------------#
@pyqtSlot()
def openimage(self):
    imgName, _ = QFileDialog.getOpenFileName(self, "打开图片", "", "Images (*.jpg, *.png);;All Files(*)")
    if len(imgName)==0:
        return
    show        = Image.open(imgName).convert("RGB")
    show        = show.resize([self.label_w, self.label_h])

    showImage   = QImage(np.array(show), np.shape(show)[1],  np.shape(show)[0], QImage.Format_RGB888)
    self.label_show_camera.setPixmap(QPixmap.fromImage(showImage))

2. Main program operation

This is to call the Example created above. Don't worry about the details. You just need to know that you can call PyQt5.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

All code

import sys
import numpy as np
from PIL import Image

from PyQt5.QtGui import QImage, QPixmap, QIcon
from PyQt5.QtCore import pyqtSlot, QSize
from PyQt5.QtWidgets import QApplication, QTextBrowser, QWidget, QLabel, QPushButton, QFileDialog


class Example(QWidget):
    def __init__(self):
        QWidget.__init__(self)
    
        #-----------------------------#
        #   界面显示相关内容
        #-----------------------------#
        self.initUI()

    def initUI(self):
        #-----------------------------#
        #   初始化标题,界面大小
        #-----------------------------#
        self.resize(640, 480)
        self.setWindowTitle('Hello World!')

        #-----------------------------#
        #   写一段话
        #   放到10,10
        #   拉伸长度为620,200
        #-----------------------------#
        self.text_browser = QTextBrowser(self)
        self.text_browser.move(10, 10)
        self.text_browser.resize(620, 30)
        self.text_browser.setText("The Hello World Before!")

        #-----------------------------#
        #   设置显示的图片
        #-----------------------------#
        self.label_h = 300
        self.label_w = 300
        self.label_show_camera = QLabel(self)
        self.label_show_camera.move(10, 50)
        self.label_show_camera.setFixedSize(self.label_w, self.label_h)
        self.label_show_camera.setText("The Hello World Before!")
        self.label_show_camera.setStyleSheet("QLabel{background:white;}")
        self.label_show_camera.setObjectName("image_show")

        #-----------------------------#
        #   获取图片按钮
        #-----------------------------#
        self.btn_photo = QPushButton('获取图片', self)
        self.btn_photo.setToolTip('点击后从电脑中读取图片')
        self.btn_photo.setIcon(QIcon("img/icon/Search.jpeg"))
        self.btn_photo.setIconSize(QSize(50, 50))
        self.btn_photo.resize(130, 60)
        self.btn_photo.move(330, 50)   
        self.btn_photo.clicked.connect(self.openimage)

        self.show()

    #-----------------------------#
    #   打开图片模式
    #-----------------------------#
    @pyqtSlot()
    def openimage(self):
        imgName, _ = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        if len(imgName)==0:
            return
        show        = Image.open(imgName).convert("RGB")
        show        = show.resize([self.label_w, self.label_h])

        showImage   = QImage(np.array(show), np.shape(show)[1],  np.shape(show)[0], QImage.Format_RGB888)
        self.label_show_camera.setPixmap(QPixmap.fromImage(showImage))
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Guess you like

Origin blog.csdn.net/weixin_44791964/article/details/130670849