create a gui calculator in python

To create a GUI calculator in Python, you can use the tkinter library. Here's a simple example:

main.py
import tkinter as tk

class Calculator(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Calculator")

        # Create a text entry widget
        self.entry = tk.Entry(self, width=20)
        self.entry.grid(row=0, column=0, columnspan=4)

        # Create buttons for the digits
        digits = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0']
        for i in range(len(digits)):
            button = tk.Button(self, text=digits[i], command=lambda digit=digits[i]: self.entry.insert(tk.END, digit))
            button.grid(row=i//3+1, column=i%3)

        # Create other buttons
        operators = ['+', '-', '*', '/']
        for i in range(len(operators)):
            button = tk.Button(self, text=operators[i], command=lambda operator=operators[i]: self.entry.insert(tk.END, operator))
            button.grid(row=i+1, column=3)

        equals_button = tk.Button(self, text='=', command=self.calculate)
        equals_button.grid(row=len(digits)//3+1, column=0, columnspan=2)

        clear_button = tk.Button(self, text='C', command=self.clear)
        clear_button.grid(row=len(digits)//3+1, column=2, columnspan=2)

    def calculate(self):
        try:
            result = eval(self.entry.get())
            self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, result)
        except Exception as e:
            self.clear()
            self.entry.insert(tk.END, "Error")

    def clear(self):
        self.entry.delete(0, tk.END)

if __name__ == "__main__":
    calculator = Calculator()
    calculator.mainloop()
1578 chars
45 lines

In this code, we use the tkinter library to create a GUI application window. Inside the Calculator class, we initialize the window and add a text entry widget for input and display. We create digit buttons and operator buttons using a loop. The calculate method evaluates the expression in the text entry and displays the result, while the clear method clears the text entry.

You can run this code to create a basic GUI calculator in Python using tkinter.

related categories

gistlibby LogSnag