Simple GUI Calculator with PyQt5
This guide demonstrates how to create a desktop calculator application using PyQt5. PyQt is a set of Python bindings for the Qt application framework, allowing you to build cross-platform GUI applications.
Modules Used:
PyQt5: The Python binding for the Qt framework.
Installation
pip install PyQt5
The Code
Save this as calculator.py.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QGridLayout, QPushButton, QLineEdit
from PyQt5.QtCore import Qt
class Calculator(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 Calculator")
self.setGeometry(100, 100, 300, 400)
self.init_ui()
def init_ui(self):
# Main Layout
main_layout = QVBoxLayout()
self.setLayout(main_layout)
# Display Screen
self.display = QLineEdit()
self.display.setAlignment(Qt.AlignRight)
self.display.setReadOnly(True)
self.display.setFixedHeight(50)
# Increase font size
font = self.display.font()
font.setPointSize(20)
self.display.setFont(font)
main_layout.addWidget(self.display)
# Buttons Layout
grid_layout = QGridLayout()
main_layout.addLayout(grid_layout)
buttons = [
('7', 0, 0), ('8', 0, 1), ('9', 0, 2), ('/', 0, 3),
('4', 1, 0), ('5', 1, 1), ('6', 1, 2), ('*', 1, 3),
('1', 2, 0), ('2', 2, 1), ('3', 2, 2), ('-', 2, 3),
('0', 3, 0), ('.', 3, 1), ('=', 3, 2), ('+', 3, 3),
('C', 4, 0)
]
for btn_text, row, col in buttons:
button = QPushButton(btn_text)
button.setFixedHeight(60)
# Connect button click to handler
button.clicked.connect(lambda checked, text=btn_text: self.on_button_click(text))
# Special styling for operators
if btn_text in ['/', '*', '-', '+', '=']:
button.setStyleSheet("background-color: <a href='/?search=%23f0ad4e' class='obsidian-tag'>#f0ad4e</a>; color: white; font-size: 18px;")
elif btn_text == 'C':
button.setStyleSheet("background-color: <a href='/?search=%23d9534f' class='obsidian-tag'>#d9534f</a>; color: white; font-size: 18px;")
else:
button.setStyleSheet("font-size: 18px;")
# Add to grid
# If it's the Clear button, make it span multiple columns for aesthetics
if btn_text == 'C':
grid_layout.addWidget(button, row, col, 1, 4)
else:
grid_layout.addWidget(button, row, col)
def on_button_click(self, text):
if text == '=':
try:
# Evaluate the expression
# Note: eval() can be dangerous if input is not controlled,
# but in a calculator with fixed buttons, it's generally acceptable for simple use.
expression = self.display.text()
result = str(eval(expression))
self.display.setText(result)
except Exception:
self.display.setText("Error")
elif text == 'C':
self.display.clear()
else:
current_text = self.display.text()
# Prevent multiple decimals
if text == '.' and '.' in current_text.split()[-1]:
return
# Handle error state reset
if current_text == "Error":
current_text = ""
self.display.setText(current_text + text)
if __name__ == "__main__":
app = QApplication(sys.argv)
calc = Calculator()
calc.show()
sys.exit(app.exec_())
Usage
- Run the script:
python calculator.py - A window will appear with a functional calculator interface.