从零基础学习PyQt5软件app开发

常见的GUI框架的梳理

GUI,全称为图形⽤户界⾯,⼜称为图形⽤户接⼝,是⼀种⼈与计算机通信的界⾯显示格式。

⽤户打开应⽤程序或⽹站时看到的第⼀个东⻄,并与之交互。

⽤户界⾯通常包括许多视觉元素,如图标、按钮、图形、显示⽂本和其他⼏种输⼊形式,如复选

框、⽂本输⼊框等。

Python有⼤量⽤于开发GUI的框架,我们在下⾯的列表中收集了⼀些最流⾏的Python GUI框架。

PyQt5

Python 对跨平台的 GUI ⼯具集 Qt 的包装实现了 440 个类以及 6000 个函数或者⽅法 ,PyQt 是

作为 Python 的插件实现的。

功能⾮常强⼤,Qt开发多美漂亮的界⾯,也就可以⽤PyQt开发多么漂亮的界⾯。

跨平台的⽀持很好。

Tkiner

绑定了 Python 的 Tk GUI ⼯具集 ,就是Python 包装的Tcl代码。

历史最悠久, Python 事实上的标准 GUI

不⽀持拖拽,所有GUI界⾯设计都必须⼿写代码

Pyside

另⼀个 Python 对跨平台的 GUI ⼯具集 Qt 的包装。

如果不做商业项⽬,强烈建议使⽤PyQt,资料多,稳定。需要开发闭源商⽤软件的就⽤PySide。

wxPYTHON

Python 对跨平台的 GUI ⼯具集 wxWidgets ( C++ 编写)的包装。

⽐较流⾏的⼀个 Tkinter 的替代品,在各种平台下表现挺好。

PyGTK

⼀系列的 Python 对 GTK+ GUI 库的包装。

在windows下表现⼀般

PyQt5

第⼀点:在PyQt中编写UI界⾯可以直接通过代码来实现,也可以通过Qt Designer来完成。

第⼆点:Qt Designer的设计符合MVC的架构,其实现了视图和逻辑的分离,从⽽实现了开发的便

捷。Qt Designer中的操作⽅式⼗分灵活,其通过拖拽的⽅式放置控件可以随时查看控件效果。

第三点:Qt Designer⽣成的.ui⽂件(实质上是XML格式的⽂件)也可以通过pyuic5⼯具转换

成.py⽂件。

配置PyQt5(windows和mac系统上的操作)

不管在Windows,还是在MAC系统下,安装了anaconda后,QtDesigner都会被安装。

所以这就是从⼀开始我就推荐⼤家安装anaconda的原因,能省去⼤家不少后续安装软件的麻烦。

既然已经安装了,剩下的问题就是找到QtDesigner的启动路径。

在Windows下,启动QtDesigner的路径是:

D:\anaconda\Library\bin

上⾯(D:\anaconda)是我在windows下的anaconda安装路径,⼤家需要替换为⾃⼰的

如下图所示:

在MAC下,启动路径是:

/Users/ksy/anaconda3/bin/Designer.app

上⾯(/Users/zhenguo/anaconda3)是我的anaconda安装路径,⼤家需要替换为⾃⼰的

如果每次都要去找到这个路径,然后启动,在PyCharm开发中,不是很⽅便。

PyCharm作为⼀个好⽤的开发利器,能帮助我们解决这个每次都要找路径然后启动的问题。

具体操作步骤,如下所示:

第⼀步:打开PyCharm

第⼆步:点击左上⻆:File

第三步:Windows选择Settings,MAC系统选择Preferences

第四步:弹出来界⾯,左侧界⾯,选择Tools,点开后选择External Tools

第五步:在弹出下⾯对话框中,依次填写:

Name:QtDesigner

Group:Qt

Program:填写上⾯QtDesigner的启动路径,在MAC下,启动路径是:

/Users/zhenguo/anaconda3/bin/Designer.app

在Windows下启动路径是:

D:\anaconda\Library\bin

Working directory:ProjectFileDir

整个界⾯填写完成后,如下所示:

利用QtDesigner设计一个计算器

ui文件转化为py文件

为什么需要将ui⽂件转为py⽂件?

如何转?

pyuic5 untitled.ui -o mainForm.py

Pycharm配置实现ui文件的自动转化py文件

Program:

Windows系统: D:\anaconda\bin\python.exe

MAC系统下: /Users/zhenguo/anaconda3/bin/python

Arguments:

-m PyQt5.uic.pyuic F i l e N a m e FileName FileName -o F i l e N a m e W i t h o u t E x t e n s i o n FileNameWithoutExtension FileNameWithoutExtension.py

Working directory:
F i l e D i r FileDir FileDir

Pycharm最终的运行效果

信号和槽函数

信号(Signal)和槽(Slot)是Qt中的核⼼机制,也是在PyQt编程中对象之间进⾏通信的机制。

在Qt中,每⼀个QObject对象和PyQt中所有继承⾃QWidget的控件都⽀持信号与槽机制。当信号

发射时,连接的槽函数将会⾃动执⾏。通过object.signal.connect()⽅法连接。

当事件或状态发⽣改变时,就会发出信号。同时,信号会触发所有与这个事件(信号)相关的函

数(槽)。信号与槽可以是多对多的关系。

使用QtDesigner操作信号和槽函数

PyQt5开发一个计算器软件

项目的整体架构

-计算器软件

-- logic.py

-- main.py

-- 计算器设计.py

-- j计算器设计.ui

计算设计.ui

本文件主要是由QtDesigner实现的

计算器设计.py

python 复制代码
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file '计算器设计.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


```python
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(783, 604)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 50, 781, 500))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton_eq = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_eq.sizePolicy().hasHeightForWidth())
        self.pushButton_eq.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_eq.setFont(font)
        self.pushButton_eq.setObjectName("pushButton_eq")
        self.gridLayout.addWidget(self.pushButton_eq, 5, 2, 1, 2)
        self.pushButton_add = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_add.sizePolicy().hasHeightForWidth())
        self.pushButton_add.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_add.setFont(font)
        self.pushButton_add.setObjectName("pushButton_add")
        self.gridLayout.addWidget(self.pushButton_add, 4, 3, 1, 1)
        self.pushButton_7 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_7.sizePolicy().hasHeightForWidth())
        self.pushButton_7.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_7.setFont(font)
        self.pushButton_7.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_7.setObjectName("pushButton_7")
        self.gridLayout.addWidget(self.pushButton_7, 1, 0, 1, 1)
        self.pushButton_sub = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_sub.sizePolicy().hasHeightForWidth())
        self.pushButton_sub.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_sub.setFont(font)
        self.pushButton_sub.setObjectName("pushButton_sub")
        self.gridLayout.addWidget(self.pushButton_sub, 2, 3, 1, 1)
        self.pushButton_0 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_0.sizePolicy().hasHeightForWidth())
        self.pushButton_0.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_0.setFont(font)
        self.pushButton_0.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_0.setObjectName("pushButton_0")
        self.gridLayout.addWidget(self.pushButton_0, 5, 0, 1, 1)
        self.pushButton_perc = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_perc.sizePolicy().hasHeightForWidth())
        self.pushButton_perc.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_perc.setFont(font)
        self.pushButton_perc.setFocusPolicy(QtCore.Qt.NoFocus)
        self.pushButton_perc.setObjectName("pushButton_perc")
        self.gridLayout.addWidget(self.pushButton_perc, 5, 1, 1, 1)
        self.pushButton_1 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_1.sizePolicy().hasHeightForWidth())
        self.pushButton_1.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_1.setFont(font)
        self.pushButton_1.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_1.setObjectName("pushButton_1")
        self.gridLayout.addWidget(self.pushButton_1, 4, 0, 1, 1)
        self.pushButton_8 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_8.sizePolicy().hasHeightForWidth())
        self.pushButton_8.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_8.setFont(font)
        self.pushButton_8.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_8.setObjectName("pushButton_8")
        self.gridLayout.addWidget(self.pushButton_8, 1, 1, 1, 1)
        self.pushButton_9 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_9.sizePolicy().hasHeightForWidth())
        self.pushButton_9.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_9.setFont(font)
        self.pushButton_9.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_9.setObjectName("pushButton_9")
        self.gridLayout.addWidget(self.pushButton_9, 1, 2, 1, 1)
        self.pushButton_M = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_M.sizePolicy().hasHeightForWidth())
        self.pushButton_M.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_M.setFont(font)
        self.pushButton_M.setStyleSheet("color: rgb(85, 170, 255);\n"
"color: rgb(170, 85, 0);")
        self.pushButton_M.setObjectName("pushButton_M")
        self.gridLayout.addWidget(self.pushButton_M, 0, 1, 1, 1)
        self.pushButton_5 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
        self.pushButton_5.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_5.setFont(font)
        self.pushButton_5.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_5.setObjectName("pushButton_5")
        self.gridLayout.addWidget(self.pushButton_5, 2, 1, 1, 1)
        self.pushButton_6 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_6.sizePolicy().hasHeightForWidth())
        self.pushButton_6.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_6.setFont(font)
        self.pushButton_6.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_6.setObjectName("pushButton_6")
        self.gridLayout.addWidget(self.pushButton_6, 2, 2, 1, 1)
        self.pushButton_RE = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_RE.sizePolicy().hasHeightForWidth())
        self.pushButton_RE.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_RE.setFont(font)
        self.pushButton_RE.setStyleSheet("color:rgb(255, 25, 28)")
        self.pushButton_RE.setObjectName("pushButton_RE")
        self.gridLayout.addWidget(self.pushButton_RE, 0, 0, 1, 1)
        self.pushButton_mul = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_mul.sizePolicy().hasHeightForWidth())
        self.pushButton_mul.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_mul.setFont(font)
        self.pushButton_mul.setObjectName("pushButton_mul")
        self.gridLayout.addWidget(self.pushButton_mul, 1, 3, 1, 1)
        self.pushButton_4 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
        self.pushButton_4.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_4.setFont(font)
        self.pushButton_4.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_4.setObjectName("pushButton_4")
        self.gridLayout.addWidget(self.pushButton_4, 2, 0, 1, 1)
        self.pushButton_div = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_div.sizePolicy().hasHeightForWidth())
        self.pushButton_div.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_div.setFont(font)
        self.pushButton_div.setObjectName("pushButton_div")
        self.gridLayout.addWidget(self.pushButton_div, 0, 3, 1, 1)
        self.pushButton_MR = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_MR.sizePolicy().hasHeightForWidth())
        self.pushButton_MR.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_MR.setFont(font)
        self.pushButton_MR.setStyleSheet("color: rgb(85, 170, 255);\n"
"color: rgb(170, 85, 0);")
        self.pushButton_MR.setObjectName("pushButton_MR")
        self.gridLayout.addWidget(self.pushButton_MR, 0, 2, 1, 1)
        self.pushButton_2 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
        self.pushButton_2.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_2.setObjectName("pushButton_2")
        self.gridLayout.addWidget(self.pushButton_2, 4, 1, 1, 1)
        self.pushButton_3 = QtWidgets.QPushButton(self.gridLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
        self.pushButton_3.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(30)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setStyleSheet("color: rgb(85, 170, 255);")
        self.pushButton_3.setObjectName("pushButton_3")
        self.gridLayout.addWidget(self.pushButton_3, 4, 2, 1, 1)
        self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget)
        self.lcdNumber.setGeometry(QtCore.QRect(0, 0, 781, 51))
        self.lcdNumber.setDigitCount(28)
        self.lcdNumber.setObjectName("lcdNumber")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 783, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_eq.setText(_translate("MainWindow", "="))
        self.pushButton_add.setText(_translate("MainWindow", "+"))
        self.pushButton_7.setText(_translate("MainWindow", "7"))
        self.pushButton_sub.setText(_translate("MainWindow", "-"))
        self.pushButton_0.setText(_translate("MainWindow", "0"))
        self.pushButton_perc.setText(_translate("MainWindow", "/100"))
        self.pushButton_1.setText(_translate("MainWindow", "1"))
        self.pushButton_8.setText(_translate("MainWindow", "8"))
        self.pushButton_9.setText(_translate("MainWindow", "9"))
        self.pushButton_M.setText(_translate("MainWindow", "M"))
        self.pushButton_5.setText(_translate("MainWindow", "5"))
        self.pushButton_6.setText(_translate("MainWindow", "6"))
        self.pushButton_RE.setText(_translate("MainWindow", "RE"))
        self.pushButton_mul.setText(_translate("MainWindow", "*"))
        self.pushButton_4.setText(_translate("MainWindow", "4"))
        self.pushButton_div.setText(_translate("MainWindow", "/"))
        self.pushButton_MR.setText(_translate("MainWindow", "MR"))
        self.pushButton_2.setText(_translate("MainWindow", "2"))
        self.pushButton_3.setText(_translate("MainWindow", "3"))
复制代码

logic.py

python 复制代码
from PyQt5 import QtWidgets

class CalState:
    READY = 0 #ready
    INPUT = 1 #input

class CalLogic:
    def __init__(self,lcd_widget:QtWidgets.QLCDNumber):
        self.lcd_widget = lcd_widget

        self.state = None
        self.stack = None #list

        self.last_opration = None
        self.current_oprator = None

        self.memory = None

    def init_cal(self):
        """初始化计算机的状态"""
        self.state = CalState.READY
        self.stack = [0]
        self.last_opration = None
        self.current_oprator = None

        self._display()

    def _display(self):
        """计算机数字显示屏的显示"""
        self.lcd_widget.display(self.stack[-1])

    def number_slot(self,num_val):
        """数字0-9的槽函数"""
        if self.state == CalState.READY:
            self.stack[-1] = num_val
            self.state = CalState.INPUT
        else:
            self.stack[-1] = self.stack[-1] * 10 + num_val
        self._display()

    def opration_slot(self,oper):
        """实现计算器+-*/四个按键的槽函数"""
        self.current_oprator = oper
        self.state = CalState.INPUT
        self.stack.append(0) #stack列表中就有2个元素[0,0]

    def perc_slot(self):
        """实现1/100按键的槽函数"""
        self.stack[-1] *= 0.01
        self._display()
        self.state = CalState.INPUT

    def eq_slot(self):
        if self.current_oprator: # 我们这个case中,+
            try:
                result = self._do_oprator(self.stack[0],self.stack[1])
            except Exception:
                self.lcd_widget.display("error")
                self.stack = [0]
                return
            self.stack = [result]
            self.current_oprator = None
            self.state = CalState.READY
            self._display() #self.statck[3]

    def _do_oprator(self,oprand1,oprand2):
        """执行加减乘除操作逻辑"""
        if self.current_oprator == "+":
            result = oprand1 + oprand2
        elif self.current_oprator == "-":
            result = oprand1 - oprand2
        elif self.current_oprator == "*":
            result = oprand1 * oprand2
        else:
            result = oprand1 / oprand2
        return result

    def re_slot(self):
        self.init_cal()

    def m_slot(self):
        self.memory = self.lcd_widget.value()

    def mr_slot(self):
        self.stack[-1] = self.memory
        self.state = CalState.INPUT

        self._display()

main.py

python 复制代码
from PyQt5.QtWidgets import *
from 计算器设计 import Ui_MainWindow
from logic import CalLogic
class MyMainWindows(QMainWindow,Ui_MainWindow):
    def __init__(self,*args,**kwargs):
        super(MyMainWindows,self).__init__(*args,**kwargs)
        self.setupUi(self)
        self.cl = CalLogic(self.lcdNumber)
        self.do_signal_slot()
        self.cl.init_cal()

    def do_signal_slot(self):
        "给数字0至9建立clicked信号和槽函数"
        self.pushButton_0.clicked.connect(lambda:self.cl.number_slot(0))
        self.pushButton_1.clicked.connect(lambda:self.cl.number_slot(1))
        self.pushButton_2.clicked.connect(lambda:self.cl.number_slot(2))
        self.pushButton_3.clicked.connect(lambda:self.cl.number_slot(3))
        self.pushButton_4.clicked.connect(lambda:self.cl.number_slot(4))
        self.pushButton_5.clicked.connect(lambda:self.cl.number_slot(5))
        self.pushButton_6.clicked.connect(lambda:self.cl.number_slot(6))
        self.pushButton_7.clicked.connect(lambda:self.cl.number_slot(7))
        self.pushButton_8.clicked.connect(lambda:self.cl.number_slot(8))
        self.pushButton_9.clicked.connect(lambda:self.cl.number_slot(9))

        """RE,M,MR"""
        self.pushButton_RE.clicked.connect(self.cl.re_slot)
        self.pushButton_RE.clicked.connect(self.cl.m_slot)
        self.pushButton_RE.clicked.connect(self.cl.mr_slot)

        """="""
        self.pushButton_eq.clicked.connect(self.cl.eq_slot)


        """给+-*/建立clicked信号和槽函数"""
        self.pushButton_add.clicked.connect(lambda :self.cl.opration_slot("+"))
        self.pushButton_sub.clicked.connect(lambda :self.cl.opration_slot("-"))
        self.pushButton_mul.clicked.connect(lambda :self.cl.opration_slot("*"))
        self.pushButton_div.clicked.connect(lambda :self.cl.opration_slot("/"))

        """1/100按键建立"""
        self.pushButton_perc.clicked.connect(self.cl.perc_slot)

if __name__ == "__main__":
    app = QApplication([])

    windows = MyMainWindows()
    windows.setWindowTitle("小丁")
    windows.show()
    app.exec_()

最终的效果

相关推荐
Re.不晚5 分钟前
Java入门15——抽象类
java·开发语言·学习·算法·intellij-idea
老秦包你会7 分钟前
Qt第三课 ----------容器类控件
开发语言·qt
凤枭香10 分钟前
Python OpenCV 傅里叶变换
开发语言·图像处理·python·opencv
ULTRA??14 分钟前
C加加中的结构化绑定(解包,折叠展开)
开发语言·c++
远望清一色30 分钟前
基于MATLAB的实现垃圾分类Matlab源码
开发语言·matlab
confiself39 分钟前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
XiaoLeisj1 小时前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee
杜杜的man1 小时前
【go从零单排】go中的结构体struct和method
开发语言·后端·golang
幼儿园老大*1 小时前
走进 Go 语言基础语法
开发语言·后端·学习·golang·go
半桶水专家1 小时前
go语言中package详解
开发语言·golang·xcode