modern-calculator/calculator.py

218 lines
6.6 KiB
Python
Raw Normal View History

2025-01-08 21:25:32 +08:00
import sys
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QGridLayout,
QPushButton,
QLineEdit,
)
from PyQt6.QtCore import Qt
2025-01-09 14:58:42 +08:00
from PyQt6.QtGui import QKeyEvent
2025-01-08 21:25:32 +08:00
class Calculator(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("现代计算器")
self.setFixedSize(400, 500)
self.setStyleSheet(
"""
QMainWindow {
background-color: #f0f0f0;
}
QLineEdit {
background-color: white;
border: 2px solid #e0e0e0;
border-radius: 8px;
padding: 10px;
margin: 10px;
font-size: 24px;
color: #333;
}
QPushButton {
background-color: white;
border: none;
border-radius: 20px;
padding: 20px;
margin: 5px;
font-size: 18px;
color: #333;
}
QPushButton:hover {
background-color: #e0e0e0;
}
QPushButton:pressed {
background-color: #d0d0d0;
}
QPushButton[type="operator"] {
background-color: #FF9500;
color: white;
}
QPushButton[type="operator"]:hover {
background-color: #FFa530;
}
QPushButton[type="equal"] {
background-color: #007AFF;
color: white;
}
QPushButton[type="equal"]:hover {
background-color: #0090FF;
}
QPushButton[type="clear"] {
background-color: #FF3B30;
color: white;
}
QPushButton[type="clear"]:hover {
background-color: #FF4B40;
}
"""
)
# 创建中心部件和网格布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
grid = QGridLayout(central_widget)
grid.setSpacing(10)
grid.setContentsMargins(20, 20, 20, 20)
# 创建显示结果的文本框
self.display = QLineEdit()
self.display.setReadOnly(True)
self.display.setAlignment(Qt.AlignmentFlag.AlignRight)
self.display.setMaxLength(15)
self.display.setMinimumHeight(80)
self.display.setText("0")
grid.addWidget(self.display, 0, 0, 1, 4)
# 按钮文本和它们的位置
buttons = {
"C": (1, 0, "clear"),
"±": (1, 1, "operator"),
"%": (1, 2, "operator"),
"/": (1, 3, "operator"),
"7": (2, 0, "number"),
"8": (2, 1, "number"),
"9": (2, 2, "number"),
"*": (2, 3, "operator"),
"4": (3, 0, "number"),
"5": (3, 1, "number"),
"6": (3, 2, "number"),
"-": (3, 3, "operator"),
"1": (4, 0, "number"),
"2": (4, 1, "number"),
"3": (4, 2, "number"),
"+": (4, 3, "operator"),
"0": (5, 0, "number"),
".": (5, 2, "number"),
"=": (5, 3, "equal"),
}
# 创建并添加按钮
for button_text, (row, col, button_type) in buttons.items():
button = QPushButton(button_text)
button.setProperty("type", button_type)
button.clicked.connect(self.button_clicked)
if button_text == "0":
grid.addWidget(button, row, col, 1, 2)
else:
grid.addWidget(button, row, col)
# 添加按键映射字典
self.key_mapping = {
Qt.Key.Key_0: "0",
Qt.Key.Key_1: "1",
Qt.Key.Key_2: "2",
Qt.Key.Key_3: "3",
Qt.Key.Key_4: "4",
Qt.Key.Key_5: "5",
Qt.Key.Key_6: "6",
Qt.Key.Key_7: "7",
Qt.Key.Key_8: "8",
Qt.Key.Key_9: "9",
Qt.Key.Key_Plus: "+",
Qt.Key.Key_Minus: "-",
Qt.Key.Key_Asterisk: "*",
Qt.Key.Key_Slash: "/",
Qt.Key.Key_Period: ".",
Qt.Key.Key_Return: "=",
Qt.Key.Key_Enter: "=",
Qt.Key.Key_Equal: "=",
Qt.Key.Key_Escape: "C",
Qt.Key.Key_Percent: "%",
}
def keyPressEvent(self, event: QKeyEvent) -> None:
"""处理键盘按键事件"""
key = event.key()
# 处理数字键盘的输入
if event.modifiers() == Qt.KeyboardModifier.KeypadModifier:
if key == Qt.Key.Key_Plus:
self.process_input("+")
elif key == Qt.Key.Key_Minus:
self.process_input("-")
elif key == Qt.Key.Key_Asterisk:
self.process_input("*")
elif key == Qt.Key.Key_Slash:
self.process_input("/")
elif key == Qt.Key.Key_Enter:
self.process_input("=")
elif key == Qt.Key.Key_Period:
self.process_input(".")
# 处理普通键盘的输入
if key in self.key_mapping:
self.process_input(self.key_mapping[key])
# 处理退格键
elif key == Qt.Key.Key_Backspace:
current_text = self.display.text()
self.display.setText(current_text[:-1])
super().keyPressEvent(event)
def process_input(self, value: str) -> None:
"""统一处理输入"""
if value == "=":
self.calculate_result()
elif value == "C":
self.display.setText("0")
else:
current_text = self.display.text()
if current_text == "0":
self.display.setText(value)
else:
new_text = current_text + value
self.display.setText(new_text)
def calculate_result(self) -> None:
"""计算结果"""
try:
current_text = self.display.text()
# 处理百分号
expression = current_text.replace("%", "/100")
# 处理正负号
expression = expression.replace("±", "-")
result = str(eval(expression))
self.display.setText(result)
except:
self.display.setText("错误")
def button_clicked(self):
"""处理按钮点击事件"""
button = self.sender()
button_text = button.text()
self.process_input(button_text)
def main():
app = QApplication(sys.argv)
calculator = Calculator()
calculator.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()