Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import sys
- from PyQt5.QtWidgets import *
- # Logic of the Program
- class Button:
- def __init__(self, text, results):
- self.b = QPushButton(str(text))
- self.text = text
- self.results = results
- self.b.clicked.connect(lambda: self.handleInput(self.text))
- # How the program handles having its buttons pushed
- def handleInput(self, v):
- # If the equals sign is pressed, evaluatate the results of the QLineEdit
- if v == "=":
- res = eval(self.results.text())
- self.results.setText(str(res))
- # If the AC button is pressed, set the results to an empty string (essentially clearing the equation)
- elif v == "AC":
- self.results.setText("")
- # If square root is pressed use function in the math module
- elif v == "√":
- value = float(self.results.text())
- self.results.setText(str(math.sqrt(value)))
- # If DEL is selected, subtract one from the line edit
- elif v == "DEL":
- current_value = self.results.text()
- self.results.setText(current_value[:-1])
- # If a number button is pressed, set the text to the value of that number
- else:
- current_value = self.results.text()
- new_value = current_value + str(v)
- self.results.setText(new_value)
- # Design of the Program
- class Application(QWidget):
- def __init__(self):
- super().__init__()
- self.setWindowTitle("Peter's Homemade Calculator")
- self.CreateApp()
- # Designing the layout of the app
- def CreateApp(self):
- # Create our grid
- grid = QGridLayout()
- # Also allows the text box for manual input
- results = QLineEdit()
- # List of buttons before initializing them
- buttons = ["AC", "√", "DEL", "/",
- 7, 8, 9, "*",
- 4, 5, 6, "-",
- 1, 2, 3, "+",
- 0, ".", "="]
- # Adding the dimensions of each button to the widget. In column and row 1 [0],
- # the button row is 1 column tall and 4 wide
- grid.addWidget(results, 0, 0, 1, 4)
- row = 1
- column = 0
- # Creating the loop to generate buttons.
- for button in buttons:
- # If column after 3, return to start new row
- if column > 3:
- column = 0
- row += 1
- # Instantiating the button object. Giving the properties button and results
- button_object = Button(button, results)
- if button == 0:
- grid.addWidget(button_object.b, row, column, 1, 2)
- column += 1
- else:
- grid.addWidget(button_object.b, row, column, 1, 1)
- column += 1
- # Tells the program to set the layout to our grid object
- self.setLayout(grid)
- # Shows the application
- self.show()
- # Runs the program
- if __name__ == "__main__":
- app = QApplication(sys.argv)
- window = Application()
- sys.exit(app.exec())
Add Comment
Please, Sign In to add comment