利用pyqt6做一个简易计算器,并且代码中带有注释
时间: 2024-02-20 07:57:43 浏览: 242
好的,以下是带有注释的一个基于 PyQt6 的简易计算器程序:
```python
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit
import sys
class Calculator(QWidget):
def __init__(self):
super().__init__()
# 设置窗口标题和大小
self.setWindowTitle("PyQt6 Calculator")
self.setGeometry(100, 100, 300, 300)
# 创建垂直布局,并将文本框添加到布局中
self.layout = QVBoxLayout()
self.textbox = QLineEdit()
self.textbox.setFixedHeight(40)
self.layout.addWidget(self.textbox)
# 创建水平布局,并向其中添加按钮
buttons_layout = QHBoxLayout()
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "C", "+",
"="
]
for button in buttons:
button_obj = QPushButton(button)
button_obj.setFixedSize(50, 50)
buttons_layout.addWidget(button_obj)
button_obj.clicked.connect(self.button_pressed)
# 将水平布局添加到垂直布局中,并将该布局设置为窗口的主布局
self.layout.addLayout(buttons_layout)
self.setLayout(self.layout)
# 按钮点击事件处理函数
def button_pressed(self):
button = self.sender()
# 如果点击的是等号,则计算表达式,并在文本框中显示结果
if button.text() == "=":
try:
result = str(eval(self.textbox.text()))
self.textbox.setText(result)
except:
self.textbox.setText("Error")
# 如果点击的是清除按钮,则清空文本框
elif button.text() == "C":
self.textbox.setText("")
# 否则将按钮的文本添加到文本框中
else:
self.textbox.setText(self.textbox.text() + button.text())
if __name__ == "__main__":
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec())
```
该程序使用 PyQt6 创建了一个简单的计算器,用户可以通过按下按钮进行数字和操作符输入,并在文本框中查看结果。程序通过 `eval()` 函数计算文本框中的表达式,并在文本框中显示结果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)