Write a simple calculator in python

1. Use a loop to add button components, and set a signal/slot for each button
2. Set a fixed size for the button: button.setFixedSize(QtCore.QSize(60,30))

3. Get the text of the sender of the event (in this case, each button):self.sender().text()

#easy calculator
import sys
from PyQt5 import QtWidgets,QtCore,QtGui
class Example(QtWidgets.QWidget):
 def __init__(self):
  super(Example, self).__init__()
  self.initUI()
  self.reset()
 def initUI(self):
  self.setWindowTitle('Simple calculator')
  grid = QtWidgets.QGridLayout()
  self.display = QtWidgets.QLineEdit('0')
  self.display.setFont(QtGui.QFont("Times", 20))
  self.display.setReadOnly(True)
  self.display.setAlignment(QtCore.Qt.AlignRight)
  self.display.setMaxLength(15)
  grid.addWidget(self.display,0,0,1,4)
  names = ['Clear', 'Back', '', 'Close',
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+']
  pos = [(0, 0), (0, 1), (0, 2), (0, 3),
    (1, 0), (1, 1), (1, 2), (1, 3),
    (2, 0), (2, 1), (2, 2), (2, 3),
    (3, 0), (3, 1), (3, 2), (3, 3 ),
    (4, 0), (4, 1), (4, 2), (4, 3)]
  c = 0
  for name in names:
   button = QtWidgets.QPushButton(name)
   button.setFixedSize(QtCore.QSize(60,30))
   button.clicked.connect(self.buttonClicked) # Set a signal/slot for each button
   if c == 2:
    pass
    #grid.addWidget(QtWidgets.QLabel(''), 0, 2) #Replace the third button with a text label!
   else:
    grid.addWidget(button, pos[c][0]+1, pos[c][1])
   c = c + 1
  self.setLayout(grid)
 def buttonClicked(self):
  #sender = self.sender(); # Determine the sender of the signal
  #self.display.setText(sender.text())
  text = self.sender().text()
  if text in '+-*/':
   self.history.append(self.number) # push the number to the stack
   self.history.append(text) # operator on the stack
   self.operator = text # set the current operator
   self.number = "" # clear the number
   self.numberType = "int"
   return
  elif text == "=":
   self.calculate() # Calculate
  elif text == "Back":
   pass
  elif text == "Clear":
   self.reset()
  elif text == "Close":
   self.close()
  elif text == ".":
   if self.numberType == "int":
    self.number += text
    self.numberType = "float"
  else:
   self.number = self.number + text if self.number != "0" else text
  self.display.setText(self.number)
 def calculate(self):
  pass
 def reset(self):
  self.number = "0"
  self.result = 0
  self.history = []
  self.operator = '' # +,-,*,/
  self.numberType = 'int' # int and float, if a decimal point is entered, it is a real number
app = QtWidgets.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325635532&siteId=291194637