python pyqt5学习记录(四)

用QT5 做一个简易的计算器界面,直接上代码:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLineEdit, QPushButton


class calc(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("计算器")

        # 数字按钮
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'C','Exit','click me'
        ]

        # 创建数字按钮和输入框
        grid = QGridLayout()
        self.display = QLineEdit()
        grid.addWidget(self.display, 0, 0, 1, 4)
        row = 1
        col = 0
        for button_text in buttons:
            button = QPushButton(button_text)
            button.clicked.connect(self.buttonClicked)
            grid.addWidget(button, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

        self.setLayout(grid)

    def buttonClicked(self):
        button = self.sender()
        text = button.text()

        if text == '=':
            try:
                result = str(eval(self.display.text()))
                self.display.setText(self.display.text() + text + result)
            except:
                self.display.setText("Error")
        elif text == 'C':
            self.display.setText('')  # 清空输入框
        elif text == 'Exit':
            self.close()  # 关闭窗口
        elif text == 'click me':
            self.display.setText('you are handsome!')
        else:
            self.display.setText(self.display.text() + text)


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

一、代码说明:

  1. 导入库: 导入 sys 和 PyQt5.QtWidgets 模块。
  2. 创建主窗口类: 创建 Calculator 类,继承自 QWidget,作为计算器主窗口。
  3. 初始化界面:
    • 设置窗口标题为 "计算器"。
    • 创建一个 QGridLayout 用于布局。
    • 创建一个 QLineEdit 作为显示输入和结果的文本框。
    • 创建一个列表 buttons,包含所有按钮的文本。
    • 使用循环遍历 buttons 列表,创建每个按钮并连接其 clicked 信号到 buttonClicked 方法。
    • 将按钮和文本框添加到 QGridLayout 中。
  4. 按钮点击事件:
    • buttonClicked 方法处理按钮点击事件。
    • 获取点击按钮的文本。
    • 如果是 "=" 按钮,则使用 eval() 函数计算表达式结果,并显示在文本框中。
    • 否则,将按钮文本添加到文本框中。
  5. 运行程序:
    • 创建 `` 对象。
    • 创建 Calculator 对象。
    • 显示计算器窗口。
    • 启动事件循环。

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kamach_83

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值