Gui Calculator
Gui Calculator
programming (OOP) involves several steps. We'll be using the Tkinter library, which is a
standard GUI library for Python.
pythonCopy code
import tkinter as tk
pythonCopy code
class Calculator:
def __init__(self, master):
self.master = master
master.title("Simple Calculator")
# Buttons
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
('C', 5, 0), ('AC', 5, 1)
]
pythonCopy code
def on_button_click(self, value):
1
if value == '=':
Page
try:
result = eval(self.entry.get())
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, str(result))
except:
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, "Error")
elif value == 'C':
current_value = self.entry.get()[:-1]
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, current_value)
elif value == 'AC':
self.entry.delete(0, tk.END)
else:
current_value = self.entry.get()
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, current_value + value)
pythonCopy code
def main():
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
if __name__ == "__main__":
main()
Explanation of Steps:
1. Import Libraries: We import the Tkinter library which provides functions for creating GUIs.
2. Create Calculator Class: We create a class called Calculator which represents our calculator
application. In the constructor __init__, we initialize the calculator window (master), set its title,
create an entry widget to display input/output, and create buttons for digits, operators, and
control functions.
3. Implement Button Click Functionality: We define a method on_button_click to handle button
clicks. Depending on the button clicked, it performs different actions such as appending the
clicked value to the input, evaluating the expression, clearing the input, etc.
4. Create the Main Function: We define a main function which creates an instance of the
Calculator class and runs the main event loop using root.mainloop().
2
Page