之前在网上看到别人写的桌面程序非常漂亮

很想自己也写出像huhumhire-hosts那样漂亮的桌面应用程序

仔细一查,原来是用PyQt写的,于是自己也下定了决心来学学这个

目前国内好像没有多少关于这方面的比较系统的入门教程

于是只好自己摸索。

一次偶然的机会,在油土鳖上看到了一个比较不错的视频

https://www.youtube.com/watch?v=DF_44sWnAsk&list=PLQVvvaa0QuDdVpDFNq4FwY9APZPGSUyR4

听了下这个大神讲的课,感觉非常不错,虽然可能需要点英语水平,不过不是什么大问题

这里就把他所讲到的这些例子给列出来吧

1、Hello World程序(QMainWindow)

    一个最简单的PyQt4窗口程序:

# -*- coding: utf-8 -*-
from PyQt4 import QtGui     # 导入PyQt4包
import sys

class Window(QtGui.QMainWindow):
    """docstring for ClassName"""
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 500)          #设置窗体大小
        self.show()                                 #显示窗体

app = QtGui.QApplication(sys.argv)
GUI = Window()                                      #将Window实例化并写入全局变量GUI
sys.exit(app.exec_())                               #设置程序出口



2、按钮控件Buttons(QPushButton)

    在上例的基础上添加代码:

# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore     # 导入PyQt4包
import sys

class Window(QtGui.QMainWindow):
    """docstring for ClassName"""
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 500)          #设置窗体大小
        self.setWindowTitle(u"PyQt4 按钮演示")       #设置窗体标题
        self.home()                                 #调用按钮初始化方法

    def home(self):
        btn = QtGui.QPushButton(u"退出程序", self)       #实例化一个按钮
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit)        #给按钮绑定事件,当点击按钮时,触发quit方法
        btn.resize(100, 100)                            #设置按钮大小
        btn.move(100, 100)                              #设置按钮所在位置
        self.show()                                 #显示窗体

app = QtGui.QApplication(sys.argv)
GUI = Window()                                      #将Window实例化并写入全局变量GUI
sys.exit(app.exec_())                               #设置程序出口


3、按钮事件控制Button Functions

    在上例的基础上添加代码:

# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore     # 导入PyQt4包
import sys

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 500)
        self.setWindowTitle(u"PyQt4 按钮演示")
        self.home()

    def home(self):
        btn = QtGui.QPushButton(u"退出程序", self)
        btn.clicked.connect(self.close_application)     #连接自身的方法
        #btn.resize(100, 100)
        #btn.move(100, 100)
        btn.resize(btn.minimumSizeHint())                 #自动决定按钮大小
        btn.move(0, 0)
        self.show()

    def close_application(self):
        sys.exit()

app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())


4、菜单栏menubar(QMenuBar)

# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore     # 导入PyQt4包
import sys

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 500)
        self.setWindowTitle(u"PyQt4 按钮演示")

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)        #退出程序选项,快捷键为G
        extractAction.setShortcut("Ctrl+Q")                                 #设置全局快捷键为Ctrl+Q
        extractAction.setStatusTip("Leave the app")                         #设置状态栏提示
        extractAction.triggered.connect(self.close_application)             #设置链接到的动作

        self.statusBar()                            #初始化状态栏

        mainMenu = self.menuBar()                   #初始化菜单栏并将菜单栏对象赋值给mainMenu
        fileMenu = mainMenu.addMenu("&File")        #添加菜单项并设置快捷键为F
        fileMenu.addAction(extractAction)           #给菜单项添加子项

        self.show()

    def close_application(self):
        sys.exit()

app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())

效果图:



5、工具栏toolbar(QToolBar)

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))
        
        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        # 从这里开始建立一个带图标的动作按钮
        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')    # 新建一个工具栏
        self.toolBar.addAction(extractAction)           # 在这个工具栏上添加按钮

        self.show()

    def close_application(self):
        print('whoaaaaa so custom!!')
        sys.exit()

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图


6、弹出消息窗口pop up message(QMessageBox)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        self.show()

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",       # 对话框标题
                                            "Get into the chopper?",    # 对话框内容
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) # 对话框选项
        # 对返回值进行判断
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图

7、复选框check box(QCheckBox)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        checkBox = QtGui.QCheckBox('Enlarge Window', self) # 实例化一个复选框选项
        checkBox.move(100, 25)  # 改变复选框的位置
        #checkBox.toggle()  # 修改复选框的状态
        checkBox.stateChanged.connect(self.enlarge_window) # 设置关联事件

        self.show()

    def enlarge_window(self, state):        # 在connect的时候,会自动绑定state参数
        if state == QtCore.Qt.Checked:      # 选中状态
            self.setGeometry(50, 50, 1000, 600)
        else:                               # 非选中状态
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图

8、进度条progress bar(QProgressBar)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(100, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)  # 实例化一个进度条控件
        self.progress.setGeometry(200, 80, 250, 20) # 设置进度条控件的位置

        self.btn = QtGui.QPushButton("Download", self)  # 实例化一个按钮,用于控制进度条
        self.btn.move(200, 120) # 修改按钮的初始位置
        self.btn.clicked.connect(self.download) # 设置按钮关联的事件

        self.show()

    def download(self):
        self.completed = 0 # 用于记录进度条的进度

        while self.completed < 100:     # 进度条最大值为100
            self.completed += 0.0001    # 递增进度
            self.progress.setValue(self.completed)  # 实时更新进度条的值


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图

9、下拉菜单drop down combobox(QComboBox)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar() # 这个方法必须要QtGui.QMainWindow这个类才有,QDialog不存在这个方法

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(100, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)

        self.btn = QtGui.QPushButton("Download", self)
        self.btn.move(200, 120)
        self.btn.clicked.connect(self.download)

        print(self.style().objectName())    # 输出当前的样式名称
        self.styleChoice = QtGui.QLabel("Windows Vista", self)  # 这是一个标签对象

        comboBox = QtGui.QComboBox(self)    # 实例化一个下拉菜单
        comboBox.addItem("motif")           # 为下拉菜单添加各种选项
        comboBox.addItem("Windows")
        comboBox.addItem("cde")
        comboBox.addItem("Plastique")
        comboBox.addItem("Cleanlooks")
        comboBox.addItem("windowsvista")


        comboBox.move(50, 250)  # 修改下拉菜单的位置
        self.styleChoice.move(50, 150)
        # Python高级特性,能将选项中的文本作为列表标识,并作为参数连接到指定方法
        comboBox.activated[str].connect(self.style_choice)  

        self.show()

    def style_choice(self, text):
        self.styleChoice.setText(text)      # 更新标签中的文本内容
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(text))   # 全局设置UI样式

    def download(self):
        self.completed = 0

        while self.completed < 100:
            self.completed += 0.0001
            self.progress.setValue(self.completed)


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()



效果图

10、字体选择器 font widget(QFontDialog)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)
        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        fontChoice = QtGui.QAction("Font", self)    # 新建一个动作按钮
        fontChoice.triggered.connect(self.font_choice)  # 链接到font_choice方法
        #self.toolBar = self.addToolBar('Font')
        self.toolBar.addAction(fontChoice)      # 将该动作按钮添加到工具栏

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(100, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)

        self.btn = QtGui.QPushButton("Download", self)
        self.btn.move(200, 120)
        self.btn.clicked.connect(self.download)

        print(self.style().objectName())
        self.styleChoice = QtGui.QLabel("Windows Vista", self)

        comboBox = QtGui.QComboBox(self)
        comboBox.addItem("motif")
        comboBox.addItem("Windows")
        comboBox.addItem("cde")
        comboBox.addItem("Plastique")
        comboBox.addItem("Cleanlooks")
        comboBox.addItem("windowsvista")

        comboBox.move(50, 250)
        self.styleChoice.move(50, 150)
        comboBox.activated[str].connect(self.style_choice)

        self.show()

    def font_choice(self):
        font, valid = QtGui.QFontDialog.getFont()       # 调用内置的字体选择对话框,并用两个变量接收返回值
        if valid:
            self.styleChoice.setFont(font)      # 修改当前字体

    def style_choice(self, text):
        self.styleChoice.setText(text)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(text))

    def download(self):
        self.completed = 0

        while self.completed < 100:
            self.completed += 0.0001
            self.progress.setValue(self.completed)


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()



效果图

11、颜色选择器与日历控件 color pickup widget and calendar(QColorDialog, QCalendarWidget)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)
        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        fontChoice = QtGui.QAction("Font", self)
        fontChoice.triggered.connect(self.font_choice)
        #self.toolBar = self.addToolBar('Font')
        self.toolBar.addAction(fontChoice)

        color = QtGui.QColor(0, 0, 0)  # 实例化一个Qt颜色
        fontColor = QtGui.QAction("Font bg Color", self)  # 实例化一个动作按钮
        fontColor.triggered.connect(self.color_picker)    # 将动作按钮关联到color_picker方法
        self.toolBar.addAction(fontColor)       # 将该动作按钮添加到工具栏

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(300, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)

        self.btn = QtGui.QPushButton("Download", self)
        self.btn.move(200, 120)
        self.btn.clicked.connect(self.download)

        print(self.style().objectName())
        self.styleChoice = QtGui.QLabel("Windows Vista", self)

        comboBox = QtGui.QComboBox(self)
        comboBox.addItem("motif")
        comboBox.addItem("Windows")
        comboBox.addItem("cde")
        comboBox.addItem("Plastique")
        comboBox.addItem("Cleanlooks")
        comboBox.addItem("windowsvista")

        comboBox.move(50, 250)
        self.styleChoice.move(50, 150)
        comboBox.activated[str].connect(self.style_choice)

        # 这里也还演示了一个日历控件,通过勾选enlarge window可以看见
        cal = QtGui.QCalendarWidget(self)   
        cal.move(500, 200)
        cal.resize(200, 200)
        
        self.show()

    def color_picker(self):
        color = QtGui.QColorDialog.getColor()       # 调用Qt内置的颜色选择器
        # Qt也使用StyleSheet,所以可以通过类似CSS修改样式的方法,修改标签文本框的背景颜色
        self.styleChoice.setStyleSheet("QWidget { background-color: %s }" % color.name())

    def font_choice(self):
        font, valid = QtGui.QFontDialog.getFont()
        if valid:
            self.styleChoice.setFont(font)

    def style_choice(self, text):
        self.styleChoice.setText(text)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(text))

    def download(self):
        self.completed = 0

        while self.completed < 100:
            self.completed += 0.0001
            self.progress.setValue(self.completed)


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()



效果图


12、文本编辑器 editor textedit(QTextEdit)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        openEditor = QtGui.QAction("&Editor", self) # 实例化一个动作按钮
        openEditor.setShortcut("Ctrl+E")    # 设置快捷键
        openEditor.setStatusTip("Open Editor")  # 设置状态提示信息
        openEditor.triggered.connect(self.editor)   # 链接到editor方法

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction) 

        editorMenu = mainMenu.addMenu("&Editor") # 在主菜单上新增一个列
        editorMenu.addAction(openEditor)    # 将动作按钮添加进Editor菜单

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)
        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        fontChoice = QtGui.QAction("Font", self)
        fontChoice.triggered.connect(self.font_choice)
        #self.toolBar = self.addToolBar('Font')
        self.toolBar.addAction(fontChoice)

        color = QtGui.QColor(0, 0, 0)
        fontColor = QtGui.QAction("Font bg Color", self)
        fontColor.triggered.connect(self.color_picker)
        self.toolBar.addAction(fontColor)

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(300, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)

        self.btn = QtGui.QPushButton("Download", self)
        self.btn.move(200, 120)
        self.btn.clicked.connect(self.download)

        print(self.style().objectName())
        self.styleChoice = QtGui.QLabel("Windows Vista", self)

        comboBox = QtGui.QComboBox(self)
        comboBox.addItem("motif")
        comboBox.addItem("Windows")
        comboBox.addItem("cde")
        comboBox.addItem("Plastique")
        comboBox.addItem("Cleanlooks")
        comboBox.addItem("windowsvista")

        comboBox.move(50, 250)
        self.styleChoice.move(50, 150)
        comboBox.activated[str].connect(self.style_choice)

        cal = QtGui.QCalendarWidget(self)
        cal.move(500, 200)
        cal.resize(200, 200)

        self.show()

    def color_picker(self):
        color = QtGui.QColorDialog.getColor()
        self.styleChoice.setStyleSheet("QWidget { background-color: %s }" % color.name())

    def editor(self):
        self.textEdit = QtGui.QTextEdit()   # 实例化一个Qt内置文本编辑器对象
        self.setCentralWidget(self.textEdit)    # 将该编辑器设置为窗体的中央主控件

    def font_choice(self):
        font, valid = QtGui.QFontDialog.getFont()
        if valid:
            self.styleChoice.setFont(font)

    def style_choice(self, text):
        self.styleChoice.setText(text)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(text))

    def download(self):
        self.completed = 0

        while self.completed < 100:
            self.completed += 0.0001
            self.progress.setValue(self.completed)


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图


13、文件选择器 file picker(QFileDialog)

# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('PyQT menubar tuts')
        self.setWindowIcon(QtGui.QIcon('footer-linkedin.png'))

        extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the App")
        extractAction.triggered.connect(self.close_application)

        openEditor = QtGui.QAction("&Editor", self)
        openEditor.setShortcut("Ctrl+E")
        openEditor.setStatusTip("Open Editor")
        openEditor.triggered.connect(self.editor)

        openFile = QtGui.QAction("&Open File", self) # 实例化一个打开文件动作按钮
        openFile.setShortcut("Ctrl+O")  # 设置快捷键
        openFile.setStatusTip("Open File")  # 设置状态提示信息
        openFile.triggered.connect(self.file_open)  # 链接file_open方法

        saveFile = QtGui.QAction("&Save File", self) # 实例化一个保存文件动作按钮
        saveFile.setShortcut("Ctrl+S")  # 设置快捷键
        saveFile.setStatusTip("Save File")  # 设置状态提示信息
        saveFile.triggered.connect(self.file_save)  # 链接file_save方法

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction)
        fileMenu.addAction(openFile)    # 给文件菜单新增打开文件选项
        fileMenu.addAction(saveFile)    # 给文件菜单新增保存文件选项

        editorMenu = mainMenu.addMenu("&Editor")    
        editorMenu.addAction(openEditor)

        self.home()

    def home(self):
        btn = QtGui.QPushButton('Quit', self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(100, 100)

        extractAction = QtGui.QAction(QtGui.QIcon('footer-linkedin.png'), "Flee the scene", self)
        extractAction.triggered.connect(self.close_application)
        self.toolBar = self.addToolBar('Extraction')
        self.toolBar.addAction(extractAction)

        fontChoice = QtGui.QAction("Font", self)
        fontChoice.triggered.connect(self.font_choice)
        #self.toolBar = self.addToolBar('Font')
        self.toolBar.addAction(fontChoice)

        color = QtGui.QColor(0, 0, 0)
        fontColor = QtGui.QAction("Font bg Color", self)
        fontColor.triggered.connect(self.color_picker)
        self.toolBar.addAction(fontColor)

        checkBox = QtGui.QCheckBox('Enlarge Window', self)
        checkBox.move(300, 25)
        #checkBox.toggle()
        checkBox.stateChanged.connect(self.enlarge_window)

        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(200, 80, 250, 20)

        self.btn = QtGui.QPushButton("Download", self)
        self.btn.move(200, 120)
        self.btn.clicked.connect(self.download)

        print(self.style().objectName())
        self.styleChoice = QtGui.QLabel("Windows Vista", self)

        comboBox = QtGui.QComboBox(self)
        comboBox.addItem("motif")
        comboBox.addItem("Windows")
        comboBox.addItem("cde")
        comboBox.addItem("Plastique")
        comboBox.addItem("Cleanlooks")
        comboBox.addItem("windowsvista")

        comboBox.move(50, 250)
        self.styleChoice.move(50, 150)
        comboBox.activated[str].connect(self.style_choice)

        cal = QtGui.QCalendarWidget(self)
        cal.move(500, 200)
        cal.resize(200, 200)

        self.show()

    def file_save(self):
        name = QtGui.QFileDialog.getSaveFileName(self, "Save File")     # 调用Qt内置的文件选择器对话框的保存方法
        file = open(name, "w")      # 用写方式打开文件
        text = self.textEdit.toPlainText()      # 转换textEdit中的文本内容
        file.write(text)    # 将文本内容写入文件
        file.close()    # 关闭file

    def file_open(self):
        name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')     # 调用Qt内置的文件选择器对话框的打开方法
        file = open(name, 'r')      # 用读方式打开文件

        self.editor()       # 启用编辑器

        with file:      # 读取文件中的所有文本
            text = file.read()
            self.textEdit.setText(text)

    def color_picker(self):
        color = QtGui.QColorDialog.getColor()
        self.styleChoice.setStyleSheet("QWidget { background-color: %s }" % color.name())

    def editor(self):
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)

    def font_choice(self):
        font, valid = QtGui.QFontDialog.getFont()
        if valid:
            self.styleChoice.setFont(font)

    def style_choice(self, text):
        self.styleChoice.setText(text)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create(text))

    def download(self):
        self.completed = 0

        while self.completed < 100:
            self.completed += 0.0001
            self.progress.setValue(self.completed)


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1000, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, "Extract!",
                                            "Get into the chopper?",
                                            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Extracting naaaaaooowwww!!")
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()


效果图