How to create a simple Calculator with GUI in Python?
In this video it shows the steps and code to create a simple UI Calculator in Python. It uses Visual Studio Code - VS Code as editor for the Python code. I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected] Details: https://programmerworld.co/blogs/how-to-create-a-simple-calculator-with-gui-in-python/ Code: import tkinter as tk from tkinter import messagebox # Create the main window root = tk.Tk() root.title("Simple Calculator") root.geometry("500x500") # Global variable for storing the expression expression = "" # Function to update the expression in the entry widget def press(num): global expression expression += str(num) equation.set(expression) # Function to evaluate the final expression def equalpress(): try: global expression total = str(eval(expression)) equation.set(total) expression = total except: equation.set("Error") expression = "" # Function to clear the expression in the entry widget def clear(): global expression expression = "" equation.set("") # Entry field for showing expression/result equation = tk.StringVar() expression_field = tk.Entry(root, textvariable=equation, font=("Arial", 20), bd=10, insertwidth=4, width=25, borderwidth=4) expression_field.grid(row=0, column=0, columnspan=4) # Button layout 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), ('C', 4, 0), ('0', 4, 1), ('=', 4, 2), ('/', 4, 3), ] # Create buttons using a loop for (text, row, col) in buttons: if text == '=': btn = tk.Button(root, text=text, height=3, width=8, font=("Arial", 18), command=equalpress) elif text == 'C': btn = tk.Button(root, text=text, height=3, width=8, font=("Arial", 18), command=clear) else: btn = tk.Button(root, text=text, height=3, width=8, font=("Arial", 18), command=lambda txt=text: press(txt)) btn.grid(row=row, column=col) # Start the GUI loop root.mainloop() --
Download
0 formatsNo download links available.