Pyqt案例讲解(实现模拟计算器效果)

Pyqt案例讲解(实现模拟计算器效果)_第1张图片

        PyQt5是一个用于Python的GUI框架,它提供了一个简单易用的GUI工具包,可以用于创建各种类型的应用程序,包括计算器。下面是一个简单的计算器的实现,其中包括了一些难点和复杂的地方。

难点:

  1. 使用Qt的布局管理器来创建窗口和控件。
  2. 使用Qt的信号和槽机制来处理用户输入和响应事件。
  3. 使用Qt的文本编辑器来编写和显示用户输入的内容。
  4. 使用Qt的图形界面设计器来创建用户界面。

复杂的地方:

  1. 需要使用Qt的信号和槽机制来处理用户输入和响应事件。这需要对Qt的语法有一定的了解。
  2. 需要使用Qt的文本编辑器来编写和显示用户输入的内容。这需要对Qt的文本编辑器有一定的了解。
  3. 需要使用Qt的图形界面设计器来创建用户界面。这需要对Qt的图形界面设计器有一定的了解。

实现的效果和利弊:

  1. 实现简单易用,可以快速上手。
  2. 可以方便地进行用户输入和响应事件的处理。
  3. 可以方便地进行用户界面的创建和编辑。
  4. 可以方便地进行用户界面的布局和排版。

实现的效果:

  1. 可以方便地进行用户输入和响应事件的处理。
  2. 可以方便地进行用户界面的创建和编辑。
  3. 可以方便地进行用户界面的布局和排版。
  4. 可以方便地进行用户界面的美化和优化。

实现的利弊:

  1. 需要对Qt的语法有一定的了解。
  2. 需要对Qt的文本编辑器有一定的了解。
  3. 需要对Qt的图形界面设计器有一定的了解。
  4. 需要对Qt的信号和槽机制有一定的了解。

ui_calculator.py

# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(600, 800)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(600, 800))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.centralwidget.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.menuButton = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.menuButton.sizePolicy().hasHeightForWidth())
        self.menuButton.setSizePolicy(sizePolicy)
        self.menuButton.setMaximumSize(QtCore.QSize(16777215, 40))
        self.menuButton.setObjectName("menuButton")
        self.horizontalLayout_2.addWidget(self.menuButton)
        self.modeLabel = QtWidgets.QLabel(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.modeLabel.sizePolicy().hasHeightForWidth())
        self.modeLabel.setSizePolicy(sizePolicy)
        self.modeLabel.setMaximumSize(QtCore.QSize(16777215, 40))
        self.modeLabel.setObjectName("modeLabel")
        self.horizontalLayout_2.addWidget(self.modeLabel)
        self.topButton = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.topButton.sizePolicy().hasHeightForWidth())
        self.topButton.setSizePolicy(sizePolicy)
        self.topButton.setMaximumSize(QtCore.QSize(16777215, 40))
        self.topButton.setObjectName("topButton")
        self.horizontalLayout_2.addWidget(self.topButton)
        spacerItem = QtWidgets.QSpacerItem(16777215, 40, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem)
        self.historyButton = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.historyButton.sizePolicy().hasHeightForWidth())
        self.historyButton.setSizePolicy(sizePolicy)
        self.historyButton.setMaximumSize(QtCore.QSize(16777215, 40))
        self.historyButton.setObjectName("historyButton")
        self.horizontalLayout_2.addWidget(self.historyButton)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.calcModeView = QtWidgets.QStackedWidget(self.centralwidget)
        self.calcModeView.setObjectName("calcModeView")
        self.pageStd = QtWidgets.QWidget()
        self.pageStd.setObjectName("pageStd")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.pageStd)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.digitUpDisplay = QtWidgets.QLineEdit(self.pageStd)
        self.digitUpDisplay.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.digitUpDisplay.setObjectName("digitUpDisplay")
        self.verticalLayout.addWidget(self.digitUpDisplay)
        self.digitDisplay = QtWidgets.QLineEdit(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.digitDisplay.sizePolicy().hasHeightForWidth())
        self.digitDisplay.setSizePolicy(sizePolicy)
        self.digitDisplay.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.digitDisplay.setObjectName("digitDisplay")
        self.verticalLayout.addWidget(self.digitDisplay)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
        self.horizontalLayout_3.setContentsMargins(0, 9, -1, -1)
        self.horizontalLayout_3.setSpacing(0)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.mcButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mcButton.sizePolicy().hasHeightForWidth())
        self.mcButton.setSizePolicy(sizePolicy)
        self.mcButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.mcButton.setFlat(True)
        self.mcButton.setObjectName("mcButton")
        self.horizontalLayout_3.addWidget(self.mcButton)
        self.mrButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mrButton.sizePolicy().hasHeightForWidth())
        self.mrButton.setSizePolicy(sizePolicy)
        self.mrButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.mrButton.setFlat(True)
        self.mrButton.setObjectName("mrButton")
        self.horizontalLayout_3.addWidget(self.mrButton)
        self.maddButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.maddButton.sizePolicy().hasHeightForWidth())
        self.maddButton.setSizePolicy(sizePolicy)
        self.maddButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.maddButton.setFlat(True)
        self.maddButton.setObjectName("maddButton")
        self.horizontalLayout_3.addWidget(self.maddButton)
        self.msubButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.msubButton.sizePolicy().hasHeightForWidth())
        self.msubButton.setSizePolicy(sizePolicy)
        self.msubButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.msubButton.setFlat(True)
        self.msubButton.setObjectName("msubButton")
        self.horizontalLayout_3.addWidget(self.msubButton)
        self.msButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.msButton.sizePolicy().hasHeightForWidth())
        self.msButton.setSizePolicy(sizePolicy)
        self.msButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.msButton.setFlat(True)
        self.msButton.setObjectName("msButton")
        self.horizontalLayout_3.addWidget(self.msButton)
        self.mlistButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mlistButton.sizePolicy().hasHeightForWidth())
        self.mlistButton.setSizePolicy(sizePolicy)
        self.mlistButton.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.mlistButton.setFlat(True)
        self.mlistButton.setObjectName("mlistButton")
        self.horizontalLayout_3.addWidget(self.mlistButton)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.gridLayout_2 = QtWidgets.QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.ceButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.ceButton.sizePolicy().hasHeightForWidth())
        self.ceButton.setSizePolicy(sizePolicy)
        self.ceButton.setObjectName("ceButton")
        self.gridLayout_2.addWidget(self.ceButton, 0, 1, 1, 1)
        self.fiveButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.fiveButton.sizePolicy().hasHeightForWidth())
        self.fiveButton.setSizePolicy(sizePolicy)
        self.fiveButton.setObjectName("fiveButton")
        self.gridLayout_2.addWidget(self.fiveButton, 3, 1, 1, 1)
        self.eightButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.eightButton.sizePolicy().hasHeightForWidth())
        self.eightButton.setSizePolicy(sizePolicy)
        self.eightButton.setObjectName("eightButton")
        self.gridLayout_2.addWidget(self.eightButton, 2, 1, 1, 1)
        self.percentButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.percentButton.sizePolicy().hasHeightForWidth())
        self.percentButton.setSizePolicy(sizePolicy)
        self.percentButton.setObjectName("percentButton")
        self.gridLayout_2.addWidget(self.percentButton, 0, 0, 1, 1)
        self.sevenButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sevenButton.sizePolicy().hasHeightForWidth())
        self.sevenButton.setSizePolicy(sizePolicy)
        self.sevenButton.setObjectName("sevenButton")
        self.gridLayout_2.addWidget(self.sevenButton, 2, 0, 1, 1)
        self.sixButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sixButton.sizePolicy().hasHeightForWidth())
        self.sixButton.setSizePolicy(sizePolicy)
        self.sixButton.setObjectName("sixButton")
        self.gridLayout_2.addWidget(self.sixButton, 3, 2, 1, 1)
        self.delButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.delButton.sizePolicy().hasHeightForWidth())
        self.delButton.setSizePolicy(sizePolicy)
        self.delButton.setObjectName("delButton")
        self.gridLayout_2.addWidget(self.delButton, 0, 3, 1, 1)
        self.divButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.divButton.sizePolicy().hasHeightForWidth())
        self.divButton.setSizePolicy(sizePolicy)
        self.divButton.setObjectName("divButton")
        self.gridLayout_2.addWidget(self.divButton, 1, 3, 1, 1)
        self.equalButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.equalButton.sizePolicy().hasHeightForWidth())
        self.equalButton.setSizePolicy(sizePolicy)
        self.equalButton.setObjectName("equalButton")
        self.gridLayout_2.addWidget(self.equalButton, 5, 3, 1, 1)
        self.subButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.subButton.sizePolicy().hasHeightForWidth())
        self.subButton.setSizePolicy(sizePolicy)
        self.subButton.setObjectName("subButton")
        self.gridLayout_2.addWidget(self.subButton, 3, 3, 1, 1)
        self.invButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.invButton.sizePolicy().hasHeightForWidth())
        self.invButton.setSizePolicy(sizePolicy)
        self.invButton.setObjectName("invButton")
        self.gridLayout_2.addWidget(self.invButton, 1, 0, 1, 1)
        self.dotButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.dotButton.sizePolicy().hasHeightForWidth())
        self.dotButton.setSizePolicy(sizePolicy)
        self.dotButton.setObjectName("dotButton")
        self.gridLayout_2.addWidget(self.dotButton, 5, 2, 1, 1)
        self.twoButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.twoButton.sizePolicy().hasHeightForWidth())
        self.twoButton.setSizePolicy(sizePolicy)
        self.twoButton.setObjectName("twoButton")
        self.gridLayout_2.addWidget(self.twoButton, 4, 1, 1, 1)
        self.threeButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.threeButton.sizePolicy().hasHeightForWidth())
        self.threeButton.setSizePolicy(sizePolicy)
        self.threeButton.setObjectName("threeButton")
        self.gridLayout_2.addWidget(self.threeButton, 4, 2, 1, 1)
        self.mulButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.mulButton.sizePolicy().hasHeightForWidth())
        self.mulButton.setSizePolicy(sizePolicy)
        self.mulButton.setObjectName("mulButton")
        self.gridLayout_2.addWidget(self.mulButton, 2, 3, 1, 1)
        self.squareButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.squareButton.sizePolicy().hasHeightForWidth())
        self.squareButton.setSizePolicy(sizePolicy)
        self.squareButton.setObjectName("squareButton")
        self.gridLayout_2.addWidget(self.squareButton, 1, 1, 1, 1)
        self.nineButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.nineButton.sizePolicy().hasHeightForWidth())
        self.nineButton.setSizePolicy(sizePolicy)
        self.nineButton.setObjectName("nineButton")
        self.gridLayout_2.addWidget(self.nineButton, 2, 2, 1, 1)
        self.sqrtButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sqrtButton.sizePolicy().hasHeightForWidth())
        self.sqrtButton.setSizePolicy(sizePolicy)
        self.sqrtButton.setObjectName("sqrtButton")
        self.gridLayout_2.addWidget(self.sqrtButton, 1, 2, 1, 1)
        self.revButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.revButton.sizePolicy().hasHeightForWidth())
        self.revButton.setSizePolicy(sizePolicy)
        self.revButton.setObjectName("revButton")
        self.gridLayout_2.addWidget(self.revButton, 5, 0, 1, 1)
        self.cButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.cButton.sizePolicy().hasHeightForWidth())
        self.cButton.setSizePolicy(sizePolicy)
        self.cButton.setObjectName("cButton")
        self.gridLayout_2.addWidget(self.cButton, 0, 2, 1, 1)
        self.zeroButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.zeroButton.sizePolicy().hasHeightForWidth())
        self.zeroButton.setSizePolicy(sizePolicy)
        self.zeroButton.setObjectName("zeroButton")
        self.gridLayout_2.addWidget(self.zeroButton, 5, 1, 1, 1)
        self.oneButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.oneButton.sizePolicy().hasHeightForWidth())
        self.oneButton.setSizePolicy(sizePolicy)
        self.oneButton.setObjectName("oneButton")
        self.gridLayout_2.addWidget(self.oneButton, 4, 0, 1, 1)
        self.fourButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.fourButton.sizePolicy().hasHeightForWidth())
        self.fourButton.setSizePolicy(sizePolicy)
        self.fourButton.setObjectName("fourButton")
        self.gridLayout_2.addWidget(self.fourButton, 3, 0, 1, 1)
        self.addButton = QtWidgets.QPushButton(self.pageStd)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.addButton.sizePolicy().hasHeightForWidth())
        self.addButton.setSizePolicy(sizePolicy)
        self.addButton.setObjectName("addButton")
        self.gridLayout_2.addWidget(self.addButton, 4, 3, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout_2)
        self.verticalLayout.setStretch(1, 2)
        self.verticalLayout.setStretch(2, 1)
        self.verticalLayout.setStretch(3, 9)
        self.calcModeView.addWidget(self.pageStd)
        self.pageProg = QtWidgets.QWidget()
        self.pageProg.setObjectName("pageProg")
        self.calcModeView.addWidget(self.pageProg)
        self.verticalLayout_2.addWidget(self.calcModeView)
        self.verticalLayout_2.setStretch(0, 1)
        self.verticalLayout_2.setStretch(1, 12)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.calcModeView.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "模拟计算器"))
        self.menuButton.setText(_translate("MainWindow", "菜单栏"))
        self.modeLabel.setText(_translate("MainWindow", "标准"))
        self.topButton.setText(_translate("MainWindow", "置顶"))
        self.historyButton.setText(_translate("MainWindow", "历史记录"))
        self.digitDisplay.setText(_translate("MainWindow", "0"))
        self.mcButton.setText(_translate("MainWindow", "MC"))
        self.mrButton.setText(_translate("MainWindow", "MR"))
        self.maddButton.setText(_translate("MainWindow", "M+"))
        self.msubButton.setText(_translate("MainWindow", "M-"))
        self.msButton.setText(_translate("MainWindow", "MS"))
        self.mlistButton.setText(_translate("MainWindow", "Mlist"))
        self.ceButton.setText(_translate("MainWindow", "CE"))
        self.fiveButton.setText(_translate("MainWindow", "5"))
        self.eightButton.setText(_translate("MainWindow", "8"))
        self.percentButton.setText(_translate("MainWindow", "%"))
        self.sevenButton.setText(_translate("MainWindow", "7"))
        self.sixButton.setText(_translate("MainWindow", "6"))
        self.delButton.setText(_translate("MainWindow", "del"))
        self.divButton.setText(_translate("MainWindow", "/"))
        self.equalButton.setText(_translate("MainWindow", "="))
        self.subButton.setText(_translate("MainWindow", "-"))
        self.invButton.setText(_translate("MainWindow", "1/x"))
        self.dotButton.setText(_translate("MainWindow", "."))
        self.twoButton.setText(_translate("MainWindow", "2"))
        self.threeButton.setText(_translate("MainWindow", "3"))
        self.mulButton.setText(_translate("MainWindow", "*"))
        self.squareButton.setText(_translate("MainWindow", "x^2"))
        self.nineButton.setText(_translate("MainWindow", "9"))
        self.sqrtButton.setText(_translate("MainWindow", "sqrt(x)"))
        self.revButton.setText(_translate("MainWindow", "+/-"))
        self.cButton.setText(_translate("MainWindow", "C"))
        self.zeroButton.setText(_translate("MainWindow", "0"))
        self.oneButton.setText(_translate("MainWindow", "1"))
        self.fourButton.setText(_translate("MainWindow", "4"))
        self.addButton.setText(_translate("MainWindow", "+"))

calcMain.py

from PyQt5 import QtWidgets
from ui_calculator import Ui_MainWindow
from enum import Enum
import operator, math
import sys

OPERATOR_DICT = {operator.add: '+', operator.sub: '-', operator.mul: '*', operator.truediv: '/'}

def stripZerosForInt(num_str):
    if '.' in num_str:
        num_str = num_str.rstrip('0').rstrip('.')
    return num_str


class status(Enum):
    INPUT_NUM1 = 1
    SET_OPERATOR = 2
    INPUT_NUM2 = 3
    CALCULATED = 4

class calcMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        #### init UI ####
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)
        '''
        Digit Display
        '''
        #### digit button ####
        self.status = status.INPUT_NUM1
        self.__newDigitFlag = True
        self.__newCalculation = False
        self.__num1 = None
        self.__num2 = None
        self.zeroButton.clicked.connect(lambda : self.inputDigit(0))
        self.oneButton.clicked.connect(lambda : self.inputDigit(1))
        self.twoButton.clicked.connect(lambda : self.inputDigit(2))
        self.threeButton.clicked.connect(lambda : self.inputDigit(3))
        self.fourButton.clicked.connect(lambda : self.inputDigit(4))
        self.fiveButton.clicked.connect(lambda : self.inputDigit(5))
        self.sixButton.clicked.connect(lambda : self.inputDigit(6))
        self.sevenButton.clicked.connect(lambda : self.inputDigit(7))
        self.eightButton.clicked.connect(lambda : self.inputDigit(8))
        self.nineButton.clicked.connect(lambda : self.inputDigit(9))
        ### dot button ###
        self.dotButton.clicked.connect(self.setDotInDigits)
        ### +/- sign button ###
        self.revButton.clicked.connect(self.setReverseSign)
        '''
        Basic Calculation function (+, -, *, /)
        '''
        self._operator = None # default use add function
        self.addButton.clicked.connect(lambda : self.setOperator(operator.add))
        self.subButton.clicked.connect(lambda : self.setOperator(operator.sub))
        self.mulButton.clicked.connect(lambda : self.setOperator(operator.mul))
        self.divButton.clicked.connect(lambda : self.setOperator(operator.truediv))
        self.equalButton.clicked.connect(self.equalFunc)
        '''
        Advance Calculation function (1/x, sqrt, x^2)
        '''
        self.invButton.clicked.connect(self.invFunc)
        self.squareButton.clicked.connect(self.squareFunc)
        self.sqrtButton.clicked.connect(self.sqrtFunc)
        '''
        Special Function Keys (%, CE, C, DEL)
        '''
        self.percentButton.clicked.connect(self.percentageFunc)
        self.ceButton.clicked.connect(self.ceFunc)
        self.cButton.clicked.connect(self.cFunc)
        self.delButton.clicked.connect(self.delFunc)
        '''
        Memory Function Keys (MC, MR, M+, M-, MS, Mlist)
        '''
        self.mcButton.setEnabled(False)
        self.mrButton.setEnabled(False)
        self.mlistButton.setEnabled(False)
        self.__memory = None
        self.mcButton.clicked.connect(self.mcFunc)
        self.mrButton.clicked.connect(self.mrFunc)
        self.maddButton.clicked.connect(self.maddFunc)
        self.msubButton.clicked.connect(self.msubFunc)
        self.msButton.clicked.connect(self.msFunc)
        self.mlistButton.clicked.connect(self.mlistFunc)

    
    #### SLOT functions ####
    ### Digits ###
    def inputDigit(self, digit):
        digit = str(digit)
        if self.status == status.INPUT_NUM1:
            if self.__newDigitFlag:
                self.digitDisplay.setText(str(digit))
                self.__newDigitFlag = False
            else:
                if self.digitDisplay.text()!='0':
                    self.digitDisplay.setText(self.digitDisplay.text()+digit)
                elif self.digitDisplay.text()=='0' and digit!='0':
                    self.digitDisplay.setText(digit)
                else:
                    pass
            self.__num1 = float(self.digitDisplay.text())
        elif self.status == status.SET_OPERATOR:
            self.__newDigitFlag = True
            self.status = status.INPUT_NUM2
            self.inputDigit(digit)
        elif self.status == status.INPUT_NUM2:
            if self.__newDigitFlag:
                self.digitDisplay.setText(str(digit))
                self.__newDigitFlag = False
            else:
                if self.digitDisplay.text()!='0':
                    self.digitDisplay.setText(self.digitDisplay.text()+digit)
                elif self.digitDisplay.text()=='0' and digit!='0':
                    self.digitDisplay.setText(digit)
                else:
                    pass
            self.__num2 = float(self.digitDisplay.text())
        elif self.status == status.CALCULATED:
            self.__newDigitFlag = True
            self.status = status.INPUT_NUM1
            self.inputDigit(digit)
        else:
            raise Exception('Unhandled status!')
    
    def setDotInDigits(self):
        if self.__newDigitFlag:
            self.digitDisplay.setText('0.')
        else:
            if '.' not in self.digitDisplay.text():
                self.digitDisplay.setText(self.digitDisplay.text()+'.')
        self.__newDigitFlag = False
    
    def setReverseSign(self):
        # if not self.__newDigitFlag:
        if self.digitDisplay.text()=='0':
            return
        num_str = self.digitDisplay.text()
        if num_str.startswith('-'):
            self.digitDisplay.setText(self.digitDisplay.text().lstrip('-'))
        else:
            self.digitDisplay.setText('-'+self.digitDisplay.text())
        if self.status in (status.INPUT_NUM1, status.CALCULATED):
            self.digitUpDisplay.setText('negate({})'.format(stripZerosForInt(num_str)))
            self.__num1 = -self.__num1
        elif self.status in (status.INPUT_NUM2, status.SET_OPERATOR):
            if self.status == status.SET_OPERATOR:
                self.__num2 = float(num_str)
                self.status = status.INPUT_NUM2
            self.__num2 = -self.__num2
        else:
            raise Exception('Unhandled status!')
        

    ### Basic Calculation Functions ###
    def setOperator(self, _operator):
        print(self.status, self.__num1, self.__num2)
        self.__newDigitFlag = True
        if self.status == status.INPUT_NUM1:
            self._operator = _operator
            self.status = status.SET_OPERATOR
        elif self.status == status.SET_OPERATOR:
            self._operator = _operator
        elif self.status == status.INPUT_NUM2:
            result = self._operator(self.__num1, self.__num2)
            self._operator = _operator
            self.status = status.SET_OPERATOR
            self.__num1 = result
            self.digitDisplay.setText(stripZerosForInt(str(result)))
        elif self.status == status.CALCULATED:
            self._operator = _operator
            self.status = status.SET_OPERATOR
        else:
            raise Exception('Unhandled status!')
        self.digitUpDisplay.setText(self.digitDisplay.text()+' '+OPERATOR_DICT[self._operator])
        
    def equalFunc(self):
        print(self.status, self.__num1, self.__num2)
        self.__newDigitFlag = True
        if self.status == status.INPUT_NUM1:
            if self._operator is None:
                self.digitUpDisplay.setText(stripZerosForInt(self.digitDisplay.text())+' =')
                self.status = status.CALCULATED
                return
            else:
                result = self._operator(self.__num1, self.__num2)
        elif self.status == status.SET_OPERATOR:
            self.__num2 = self.__num1
            result = self._operator(self.__num1, self.__num2)
        elif self.status == status.INPUT_NUM2:
            result = self._operator(self.__num1, self.__num2)
        elif self.status ==status.CALCULATED:
            result = self._operator(self.__num1, self.__num2)
        else:
            raise Exception('Unhandled status!')
        self.digitUpDisplay.setText(stripZerosForInt(str(self.__num1))+' '+OPERATOR_DICT[self._operator]+' '+ stripZerosForInt(str(self.__num2)) +' =')
        self.digitDisplay.setText(stripZerosForInt(str(result)))
        self.__num1 = result
        self.status = status.CALCULATED

    ### Advance Calculation Functions  ###
    def invFunc(self):
        # inverse the number: 1/x
        __num = float(self.digitDisplay.text())
        if __num == 0:
            self.digitDisplay.setText("Error! Zero on denominator!")
            return
        res = 1/__num
        num_str = self.digitDisplay.text()
        if self.status in (status.INPUT_NUM1, status.CALCULATED):
            self.digitUpDisplay.setText('1/{}'.format(stripZerosForInt(num_str)))
            self.__num1 = res
        elif self.status in (status.INPUT_NUM2, status.SET_OPERATOR):
            if self.status == status.SET_OPERATOR:
                self.__num2 = float(num_str)
                self.status = status.INPUT_NUM2
            self.__num2 = res
        else:
            raise Exception('Unhandled status!')
        self.digitDisplay.setText(str(res))
        self.__newDigitFlag = True
    
    def squareFunc(self):
        # x^2
        __num = float(self.digitDisplay.text())
        res = __num**2
        num_str = self.digitDisplay.text()
        if self.status in (status.INPUT_NUM1, status.CALCULATED):
            print(num_str)
            self.digitUpDisplay.setText('sqr({})'.format(stripZerosForInt(num_str)))
            self.__num1 = res
        elif self.status in (status.INPUT_NUM2, status.SET_OPERATOR):
            if self.status == status.SET_OPERATOR:
                self.__num2 = float(num_str)
                self.status = status.INPUT_NUM2
            self.__num2 = res
        else:
            raise Exception('Unhandled status!')
        self.digitDisplay.setText(str(res))
        self.__newDigitFlag = True
    
    def sqrtFunc(self):
        # sqrt(x)
        __num = float(self.digitDisplay.text())
        res = math.sqrt(__num)
        num_str = self.digitDisplay.text()
        if self.status in (status.INPUT_NUM1, status.CALCULATED):
            self.digitUpDisplay.setText('sqrt({})'.format(stripZerosForInt(num_str)))
            self.__num1 = res
        elif self.status in (status.INPUT_NUM2, status.SET_OPERATOR):
            if self.status == status.SET_OPERATOR:
                self.__num2 = float(num_str)
                self.status = status.INPUT_NUM2
            self.__num2 = res
        else:
            raise Exception('Unhandled status!')
        self.digitDisplay.setText(str(res))
        self.__newDigitFlag = True
    
    ### Special function keys ###
    def percentageFunc(self):
        pass

    def ceFunc(self):
        # if pressed during digits input, clear all the edit digits
        # if pressed after calculation, clear all
        self.digitDisplay.setText("0")
        if self.__newDigitFlag:
            self.digitUpDisplay.setText("")

    def cFunc(self):
        # set all clear
        self.digitUpDisplay.setText("")
        self.digitDisplay.setText("0")
        self.__num1 = 0
        self.__num2 = None
        self._operator = None
        self.__newDigitFlag = True
        self.status = status.INPUT_NUM1

    def delFunc(self):
        # if del during digits input, delete the last digit
        # if del after calculation, clear calculation display (self.digitUpDisplay)
        if not self.__newDigitFlag:
            currentStr = self.digitDisplay.text()
            if len(currentStr)>1:
                newStr = currentStr[:-1]
            else:
                newStr = "0"
            self.digitDisplay.setText(newStr)
        else:
            self.digitUpDisplay.setText("")    

    ### Memory function keys ###
    def mcFunc(self):
        # clear memory
        self.__memory = None
        self.mcButton.setEnabled(False)
        self.mrButton.setEnabled(False)
        self.mlistButton.setEnabled(False)
        self.__newDigitFlag = True

    def mrFunc(self):
        # recall memory
        self.digitDisplay.setText(str(self.__memory))
        self.__newDigitFlag = True
        if self.status in (status.INPUT_NUM2, status.SET_OPERATOR):
            if self.status == status.SET_OPERATOR:
                self.status = status.INPUT_NUM2
            self.__num2 = self.__memory
        elif self.status in (status.INPUT_NUM1, status.CALCULATED):
            if self.status == status.CALCULATED:
                self.status = status.INPUT_NUM1
            self.__num1 = self.__memory
        else:
            raise Exception('Unhandled status')

    def maddFunc(self):
        # add to memroy
        if self.__memory is None:
            self.mcButton.setEnabled(True)
            self.mrButton.setEnabled(True)
            self.mlistButton.setEnabled(True)
            self.__memory = 0
        _num = float(self.digitDisplay.text())
        self.__memory += _num
        self.__newDigitFlag = True

    def msubFunc(self):
        # substract to memroy
        if self.__memory is None:
            self.mcButton.setEnabled(True)
            self.mrButton.setEnabled(True)
            self.mlistButton.setEnabled(True)
            self.__memory = 0
        _num = float(self.digitDisplay.text())
        self.__memory -= _num
        self.__newDigitFlag = True
    
    def msFunc(self):
        # save memory
        if self.__memory is None:
            self.mcButton.setEnabled(True)
            self.mrButton.setEnabled(True)
            self.mlistButton.setEnabled(True)
            self.__memory = 0
        _num = float(self.digitDisplay.text())
        self.__memory = _num
        self.__newDigitFlag = True

    def mlistFunc(self):
        pass

if __name__ == '__main__':
    # launch the window
    app = QtWidgets.QApplication(sys.argv)
    win = calcMainWindow()
    win.show()
    sys.exit(app.exec_())

你可能感兴趣的:(Pyqt技术教程专栏,pyqt)