基于PyQt(Python+QT)的gui程序开发 (转)

最近帮朋友做了一个将文本文件按条件导出到excel里面的小程序。使用了PyQT,发现Python真是一门强大的脚本语言,开发效率极高。

首先需要引用

[python] view plain copy
  1. from PyQt4 import QtGui, uic, QtCore   


很多控件像QPushButton是从QtGui的空间中得来的,下面def __init__(self, parent=None)中定义了界面的设计及与控件相互联系的方法。

[python] view plain copy
  1. class AddressBook(QtGui.QWidget):  
  2.     def __init__(self, parent=None):  
  3.         super(AddressBook, self).__init__(parent)  
  4.         #button控件  
  5.         self.out_put = QtGui.QPushButton("&Out_put")  
  6.         #该button在被单击之后,调用self.out的方法  
  7.         self.out_put.clicked.connect(self.out)  
  8.         browseButton = self.createButton("&Browse..."self.browse)  
  9.    
  10.         nameLabel = QtGui.QLabel("Location:")  
  11.         self.nameLine = QtGui.QLineEdit()  
  12.         addressLabel = QtGui.QLabel("Loading:")  
  13.         self.addressText = QtGui.QTextEdit()  
  14.         self.createFilesTable()  
  15.   
  16.         buttonLayout1 = QtGui.QVBoxLayout()  
  17.         buttonLayout1.addWidget(browseButton, QtCore.Qt.AlignTop)  
  18.         buttonLayout1.addWidget(self.out_put)  
  19.         buttonLayout1.addStretch()  
  20.         #界面的布局  
  21.         mainLayout = QtGui.QGridLayout()  
  22.         mainLayout.addWidget(nameLabel, 00)  
  23.         mainLayout.addWidget(self.nameLine, 01)  
  24.         mainLayout.addWidget(addressLabel, 10, QtCore.Qt.AlignTop)  
  25.         #mainLayout.addWidget(self.addressText, 1, 1)  
  26.         mainLayout.addWidget(self.filesTable, 11)  
  27.         mainLayout.addLayout(buttonLayout1, 12)  
  28.         self.setLayout(mainLayout)  
  29.         self.setWindowTitle("HD_export")  


得到的效果如图所示:

基于PyQt(Python+QT)的gui程序开发 (转)_第1张图片

然后就是定义button对应的方法。如Browse这个button对应的方法,代码如下:

[python] view plain copy
  1. def browse(self):  
  2.         directory = QtGui.QFileDialog.getExistingDirectory(self"Find Files",  
  3.                 QtCore.QDir.currentPath())  
  4.   
  5.         self.nameLine.setText(directory)  
  6.         self.find()  
  7.           
  8.     def find(self):  
  9.         self.filesTable.setRowCount(0)  
  10.         path=self.nameLine.text()  
  11.         self.currentDir = QtCore.QDir(path)  
  12.         files = self.currentDir.entryList(QtCore.QDir.Files | QtCore.QDir.NoSymLinks)  
  13.   
  14.         self.showFiles(files)  


 

这样当单击Browse这个按钮的时候,他就会调用browse这个方法了。

     Ok,这样PyQT的用法就差不多说完了。然后就是如果编译这个.py文件,让他能够生成可用的.exe.

     我在生成的时候,使用的是cx_Freeze,它的用法就一个命令FreezePython.exe,打包也很快捷:

 cx_Freeze.bat  --install-dir="/your/path/to/install" app.py      

在安装的时候他会把cx_Freeze.bat放到\Python27\Scripts的文件夹中。

真正理解这个GUI开发,还是要自己去动手做。使用PyQT可以迅速的开发出自己想要的小工具,是一个不错的方法

 

你可能感兴趣的:(python,qt,PyQt,程序开发)