当前位置:网站首页>python开发qt程序读取图片的简单流程

python开发qt程序读取图片的简单流程

2020-11-08 16:17:00 spiritboy

一. python 安装pyqt5

pip install pyqt5 -i https://mirrors.aliyun.com/pypi/simple

二. 安装qt designer(设计生成程序界面ui)

下载地址

(官方)https://build-system.fman.io/qt-designer-download
(csdn)https://download.csdn.net/download/qq_26696715/13094628
(加群下载)686070107

三. 使用qt designer设计生成ui文件

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>635</width>
    <height>511</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Dialog</string>
  </property>
  <widget class="QPushButton" name="pushButton">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>10</y>
     <width>81</width>
     <height>31</height>
    </rect>
   </property>
   <property name="font">
    <font>
     <pointsize>12</pointsize>
     <weight>75</weight>
     <bold>true</bold>
    </font>
   </property>
   <property name="text">
    <string>选择图片</string>
   </property>
  </widget>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>70</y>
     <width>581</width>
     <height>401</height>
    </rect>
   </property>
   <property name="text">
    <string/>
   </property>
   <property name="pixmap">
    <pixmap>img/1.tif</pixmap>
   </property>
   <property name="scaledContents">
    <bool>true</bool>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

四. 将ui文件转换成py文件

pyuic5 -o ui.py ui.ui

五. 编写main.py文件调用ui.py文件

# -*- coding: utf-8 -*-

import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import cv2
import qimage2ndarray
from ui import Ui_Dialog

class mwindow(QWidget, Ui_Dialog):
    def __init__(self):
        super(mwindow, self).__init__()
        self.setupUi(self)
        
    #选择图片
    def openimage(self):
        #选择图片
        imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "img", "*.jpg;*.tif;*.png;;All Files(*)")
        if imgName=="":
            return 0
        #qt5读取图片
        jpg = QPixmap(imgName).scaled(self.label.width(), self.label.height())
        #显示原图
        self.label.setPixmap(jpg)
if __name__ == '__main__':
    app=QApplication(sys.argv)
    #初始化窗口
    m=mwindow()
    #绑定按钮事件
    m.pushButton.clicked.connect(m.openimage)#选择图片
    m.show()
    sys.exit(app.exec_())

六. 运行main.py文件

python main.py

有问题添加QQ群:686070107

版权声明
本文为[spiritboy]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/3337401/blog/4708233