pyqt5 把.ui文件转换成.py文件 及转换后的使用

首先运行以下代码,它会把当前目录下所有的.ui文件转换成.py文件

import os
import os.path

dir = './'  # 文件所在的路径


# 找出路径下所有的.ui文件
def listUiFile():
    list = []
    files = os.listdir(dir)
    for filename in files:
        # print(filename)
        if os.path.splitext(filename)[1] == '.ui':
            list.append(filename)

    return list


# 把扩展名未.ui的转换成.py的文件
def transPyFile(filename):
    return os.path.splitext(filename)[0] + '.py'


# 通过命令把.ui文件转换成.py文件
def runMain():
    list = listUiFile()
    for uifile in list:
        pyfile = transPyFile(uifile)
        cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=pyfile, uifile=uifile)
        os.system(cmd)


if __name__ == "__main__":
    runMain()

然后将ui装载进你的主程序

pyqt5 把.ui文件转换成.py文件 及转换后的使用

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

# Form implementation generated from reading ui file 'MyForm.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1492, 1097)
        #...以下省略数行    
        #...以下省略数行 
        #...以下省略数行 

pyqt5 把.ui文件转换成.py文件 及转换后的使用

import sys

from PyQt5.QtWidgets import QApplication, QWidget

from MyForm import Ui_Form


def main():

    #创建QApplication类的实例
    app = QApplication(sys.argv)
    form = QWidget()
    window = Ui_Form()
    window.setupUi(form)
    form.show()
    sys.exit(app.exec_())
if __name__ == '__main__':

    main()

https://www.jianshu.com/p/7948e3d3801b

上一篇:Ubuntu下Pycharm配置pyqt5来做界面


下一篇:【pyinstaller打包PyQT5程序成exe可执行文件】