首页 > 其他分享 >Pyqt5 实现计算器

Pyqt5 实现计算器

时间:2024-09-13 13:53:47浏览次数:10  
标签:实现 text self Pyqt5 num 计算器 line txt display

计算器是练习pyqt5的好项目

界面设计简单

 代码如下:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.display = None
        self.buttons = None
        self.names = None
        self.current_text = None
        self.first_num = None
        self.operation = None
        self.ui()
        self.show()

    def ui(self):  # 设置窗口
        self.setFixedSize(300, 400)
        self.setWindowTitle('计算器')

        # 创建布局框架
        main_layout = QVBoxLayout()
        grid = QGridLayout()
        h_layout = QHBoxLayout()
        # 设置文本框
        self.display = QLineEdit(self)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setReadOnly(True)

        # 文本框添加进入布局
        main_layout.addWidget(self.display)

        # 定义按键元素
        data = {
            0: ['7', '8', '9', '/'],
            1: ['4', '5', '6', '*'],
            2: ['1', '2', '3', '-'],
            3: ['0', '00', '.', '+']
        }

        # 创建两个字典,一个放按钮名字,一个放按钮
        self.names = {}
        self.buttons = {}
        for line_number0, line_data0 in data.items():
            self.names[line_number0] = []
            for a0, b0 in enumerate(line_data0):
                self.names[line_number0].append('btn_' + str(line_number0) + '_' + str(a0))
        for line_number, line_data in data.items():
            self.buttons[line_number] = []
            for a, b in enumerate(line_data):
                self.names[line_number][a] = QPushButton(b)
                self.buttons[line_number].append(self.names[line_number][a])
                grid.addWidget(self.names[line_number][a], line_number, a)  # 按名称创建按钮
        for a0 in range(4):
            for b0 in range(3):
                self.buttons[a0][b0].clicked.connect(lambda checked, num=data[a0][b0]: self.btn_click(num))  # 按钮连接单击信号函数

        # 运算符号按钮连接运算函数
        self.names[0][3].clicked.connect(self.divide)
        self.names[1][3].clicked.connect(self.multiply)
        self.names[2][3].clicked.connect(self.subtract)
        self.names[3][3].clicked.connect(self.add)

        main_layout.addLayout(grid)  # 把九宫格布局扔进主布局

        # 创建清零按钮和等号按钮,并连接各自的函数
        btn_ce = QPushButton('CE')
        h_layout.addWidget(btn_ce)
        btn_ce.clicked.connect(self.btn_ce_click)
        btn_equal = QPushButton('=')
        h_layout.addWidget(btn_equal)
        btn_equal.clicked.connect(self.equal)
        main_layout.addLayout(h_layout)

        self.setLayout(main_layout)

    def btn_click(self, txt):  # 数字输入函数
        self.current_text = self.display.text()
        if self.current_text == '' and txt == '00':
            txt = '0'
        if self.current_text == '0' and txt == '00':
            txt = ''
        if self.current_text == '0' and txt == '0':
            txt = ''
        if self.current_text == '' and txt == '.':
            txt = '0.'
        if '.' in [x for x in self.current_text] and txt == '.':
            txt = ''

        self.display.setText(self.current_text + txt)

    def btn_ce_click(self):  # 清零函数
        self.display.clear()
        self.first_num = None
        self.operation = None

    def add(self):  # 加法
        self.first_num = float(self.display.text())
        self.display.clear()
        self.operation = 'add'

    def subtract(self):  # 减法
        self.first_num = float(self.display.text())
        self.display.clear()
        self.operation = 'subtract'

    def multiply(self):  # 乘法
        self.first_num = float(self.display.text())
        self.display.clear()
        self.operation = 'multiply'

    def divide(self):  # 除法
        self.first_num = float(self.display.text())
        self.display.clear()
        self.operation = 'divide'

    def equal(self):  # 计算结果并显示
        second_num = float(self.display.text())
        self.display.clear()
        result = ''

        if self.operation == "add":
            result = self.first_num + second_num
        elif self.operation == "subtract":
            result = self.first_num - second_num
        elif self.operation == "multiply":
            result = self.first_num * second_num
        elif self.operation == "divide":
            if second_num == 0:
                result = "除数不能为 0"
            else:
                result = self.first_num / second_num
        self.display.setText(str(result))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec_())

标签:实现,text,self,Pyqt5,num,计算器,line,txt,display
From: https://blog.csdn.net/2301_79578337/article/details/142209212

相关文章