graphical interface for calc in python

To create a graphical interface for a calculator in Python, we can use the tkinter module, which allows us to create GUI applications easily. Here's a simple example:

main.py
from tkinter import *

# Create a window
window = Tk()

# Set window title
window.title("Calculator")

# Add an entry widget for input
input_field = Entry(window, width=35, borderwidth=5)
input_field.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

# Define button click function
def button_click(number):
    current = input_field.get()
    input_field.delete(0, END)
    input_field.insert(0, str(current) + str(number))

# Define clear function
def button_clear():
    input_field.delete(0, END)

# Define add function
def button_add():
    first_number = input_field.get()
    global f_num
    global math_operation
    math_operation = "addition"
    f_num = int(first_number)
    input_field.delete(0, END)

# Define equal function
def button_equal():
    second_number = input_field.get()
    input_field.delete(0, END)

    if math_operation == "addition":
        input_field.insert(0, f_num + int(second_number))

# Define buttons
button_1 = Button(window, text="1", padx=40, pady=20, command=lambda: button_click(1))
button_2 = Button(window, text="2", padx=40, pady=20, command=lambda: button_click(2))
button_3 = Button(window, text="3", padx=40, pady=20, command=lambda: button_click(3))
button_4 = Button(window, text="4", padx=40, pady=20, command=lambda: button_click(4))
button_5 = Button(window, text="5", padx=40, pady=20, command=lambda: button_click(5))
button_6 = Button(window, text="6", padx=40, pady=20, command=lambda: button_click(6))
button_7 = Button(window, text="7", padx=40, pady=20, command=lambda: button_click(7))
button_8 = Button(window, text="8", padx=40, pady=20, command=lambda: button_click(8))
button_9 = Button(window, text="9", padx=40, pady=20, command=lambda: button_click(9))
button_0 = Button(window, text="0", padx=40, pady=20, command=lambda: button_click(0))
button_add = Button(window, text="+", padx=39, pady=20, command=button_add)
button_equal = Button(window, text="=", padx=91, pady=20, command=button_equal)
button_clear = Button(window, text="Clear", padx=79, pady=20, command=button_clear)

# Put the buttons on the window
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)

button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)

button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)

button_0.grid(row=4, column=0)
button_clear.grid(row=4, column=1, columnspan=2)
button_add.grid(row=5, column=0)
button_equal.grid(row=5, column=1, columnspan=2)

# Run the window
window.mainloop()
2570 chars
75 lines

This example creates a simple calculator with addition operation. You can modify the code to add other operations and functionalities.

gistlibby LogSnag