Advertisement
Muhammad_Farroos

calculator GUI

Dec 27th, 2023
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. import sys
  2. from PyQt5.QtCore import Qt
  3. from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QLineEdit, QVBoxLayout
  4.  
  5. class SimpleCalculator(QWidget):
  6.     def __init__(self):
  7.         super().__init__()
  8.  
  9.         self.initUI()
  10.  
  11.     def initUI(self):
  12.         self.input_line = QLineEdit(self)
  13.         self.input_line.setAlignment(Qt.AlignRight)
  14.         self.input_line.setReadOnly(True)
  15.  
  16.         buttons = [
  17.             '7', '8', '9', '/',
  18.             '4', '5', '6', '*',
  19.             '1', '2', '3', '-',
  20.             '0', 'C', '=', '+'
  21.         ]
  22.  
  23.         grid_layout = QGridLayout()
  24.         row, col = 0, 0
  25.  
  26.         for button_text in buttons:
  27.             button = QPushButton(button_text, self)
  28.             button.clicked.connect(lambda _, ch=button_text: self.buttonClicked(ch))
  29.             grid_layout.addWidget(button, row, col)
  30.             col += 1
  31.             if col > 3:
  32.                 col = 0
  33.                 row += 1
  34.  
  35.         main_layout = QVBoxLayout()
  36.         main_layout.addWidget(self.input_line)
  37.         main_layout.addLayout(grid_layout)
  38.         self.setLayout(main_layout)
  39.  
  40.         self.setGeometry(300, 300, 300, 400)
  41.         self.setWindowTitle('Kalkulator Sederhana')
  42.         self.show()
  43.  
  44.     def buttonClicked(self, buttonText):
  45.         if buttonText == '=':
  46.             try:
  47.                 result = eval(self.input_line.text())
  48.                 self.input_line.setText(str(result))
  49.             except Exception as e:
  50.                 self.input_line.setText('Error')
  51.         elif buttonText == 'C':
  52.             self.input_line.clear()
  53.         else:
  54.             current_text = self.input_line.text()
  55.             new_text = current_text + buttonText
  56.             self.input_line.setText(new_text)
  57.  
  58. def main():
  59.     app = QApplication(sys.argv)
  60.     calculator = SimpleCalculator()
  61.     sys.exit(app.exec_())
  62.  
  63. main()
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement