欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

python + PyQt5 实现 简易计算器

程序员文章站 2022-07-26 11:10:43
忽然想起之前一直想写个简单的计算器,今天就写了一下,界面有些简陋,但是基本功能实现没有问题 以下是源码: ......

忽然想起之前一直想写个简单的计算器,今天就写了一下,界面有些简陋,但是基本功能实现没有问题

python + PyQt5 实现 简易计算器

以下是源码:

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


class Calculator(QtWidgets.QWidget):

    def __init__(self):
        super(Calculator, self).__init__()
        self.initUI()
        self.reset()
        self.display.setText("0")

    def initUI(self):
        self.resize(600,650)
        self.setWindowTitle('简易计算器')
        Grid = QtWidgets.QGridLayout()

        self.display = QtWidgets.QLineEdit('')
        self.display.setFont(QFont("Times", 20))
        self.display.setReadOnly(True)
        self.display.setAlignment(QtCore.Qt.AlignRight)
        self.display.setMaxLength(20)
        Grid.addWidget(self.display, 0, 0, 1, 4)

        names = ['C', '(', 'Del', '+',
                 '7', '8', '9', '-',
                 '4', '5', '6', '*',
                 '1', '2', '3', '/',
                 '0', '.', ')', '=']
        pos = [(0, 0), (0, 1), (0, 2), (0, 3),
               (1, 0), (1, 1), (1, 2), (1, 3),
               (2, 0), (2, 1), (2, 2), (2, 3),
               (3, 0), (3, 1), (3, 2), (3, 3),
               (4, 0), (4, 1), (4, 2), (4, 3)]
        c = 0
        for name in names:
            button = QtWidgets.QPushButton(name)
            button.setFixedSize(QtCore.QSize(100, 60))
            button.setFont(QFont('Times', 30))
            button.clicked.connect(self.ButtonClicked)  
            Grid.addWidget(button, pos[c][0] + 1, pos[c][1])
            c = c + 1

        self.setLayout(Grid)

    def ButtonClicked(self):
        text = self.sender().text()
        if text == "=":
            r = eval(self.number)
            result = str(r).decode('utf-8')
            self.display.setText(str(result))  #计算结果
            self.number = result

        elif text == "Del":
            self.number = self.number[:-1]
            self.display.setText(self.number)

        elif text == "C":
            self.reset()
            self.display.setText(self.number)

        else:
            if text in "+-*/":
                self.number = self.number + text
            else:
                self.number = self.number + text if self.number != "0" else text
            self.display.setText(self.number)

    def reset(self):
        self.number = "0"


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Calculator()
    ex.show()
    sys.exit(app.exec_())