0% found this document useful (0 votes)
27 views

Practical Assignment 28

The document describes how to create a GUI application in Python using Tkinter to build a basic calculator app. It provides code to define buttons for numbers and operators and handle button clicks to perform calculations and display results.

Uploaded by

Tahir Pirjade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Practical Assignment 28

The document describes how to create a GUI application in Python using Tkinter to build a basic calculator app. It provides code to define buttons for numbers and operators and handle button clicks to perform calculations and display results.

Uploaded by

Tahir Pirjade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Roll No :58

Assignment 28

Q.Write a GUI application to perform arithmetic calculations like addition,


subtraction, multiplication, division.

 Code : -
import tkinter as tk

class CalculatorApp:

def __init__(self, master):

self.master = master

self.master.title("Simple Calculator")

self.result_var = tk.StringVar()

self.entry = tk.Entry(master, textvariable=self.result_var, font=("Arial",


14), justify="right")

self.entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10,


sticky="nsew")

# Define 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),

# Create and place buttons

for (text, row, col) in buttons:


button = tk.Button(master, text=text, font=("Arial", 14),
command=lambda t=text: self.on_button_click(t))

button.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

# Configure grid to expand with window resizing

for i in range(5):

master.grid_rowconfigure(i, weight=1)

master.grid_columnconfigure(i, weight=1)

def on_button_click(self, button_text):

current_text = self.result_var.get()

if button_text == "=":

try:

result = eval(current_text)

self.result_var.set(result)

except Exception as e:

self.result_var.set("Error")

else:

current_text += button_text

self.result_var.set(current_text)

# Create the main window

root = tk.Tk()

# Create an instance of the CalculatorApp class

app = CalculatorApp(root)
# Start the main loop

root.mainloop()

 OUTPUT : -

You might also like