CalcPy 2.0 – The second and final part of calculator

Ok, this is the finale code. In the next post I will show the live coding. Until then, let’s take a look at the code for this calculator app made with python and tkinter.

import tkinter as tk
import tkinter.ttk as ttk

counter = 0
crow = 0
mem1 = ""
mem2 = ""
mop = ""
def setEntry(value):
    global esv
    global mem1
    global mem2
    global mop

    print(value)

    if value == "CE":
        esv.set("")
    else:
        v = esv.get()
        v += value
        esv.set(v)

        # when you press this... you must put the value in mem1
        # but you must not add other values
        if value in "+-x:":
            mop = value
            print("mop", mop)
            mem1 = v.replace(value, "")
            esv.set("")

        elif value == "=":
            mem2 = v.replace("=","")
            print("mem", mop)
            if mop == "x":
                mop = "*"
            if mop == ":":
                mop = "/"
            result = eval(f"{float(mem1)} {mop} {float(mem2)}")
            esv.set(result)
            mem1 = result
        # Here is when user digit a number
        else:
            # it is the first number, mem it and show it
            if mem1 == "":
                mem1 = value
                esv.set(value)
            # the second number show the first and the second, memorize it
            elif mop == "":
                value = str(mem1) + value
                mem1 = value
                esv.set(value)
            if mem1 == mem2:
                value = str(mem2) + value
                mem2 = value
                esv.set(value)




def Button(text):
    global counter
    global crow
    global entry
    global esv

    b = tk.Button(root, text=text)
    root.columnconfigure(counter, weight=1)
    b["command"] = lambda: setEntry(b["text"])
    if b["text"] == "CE":
        b["bg"] = "green"
    b.grid(row=1+crow, column=counter, sticky="nswe",ipady=10, ipadx=10)
    counter += 1
    if counter > 2:
        crow +=1
        counter = 0
    return b


def main():
    global root
    global esv

    root = tk.Tk()
    root.title("CalpPy")
    esv = tk.StringVar()
    entry = tk.Entry(root, textvariable=esv, justify="right")
    entry["font"] = "arial 24"
    entry["bg"] = "cyan"
    entry.grid(row=0, column=0, columnspan=3, sticky="nswe")

    # Buttons

    for but in [7, 8, 9, 4, 5, 6,
                1, 2, 3, 0, "+", "-",
                "x", ":", "=", "CE"]:
        b = Button(str(but))

    root.mainloop()

main()

The video with the full code of the calculator app with tkinter

A non resizablem calculator

# custom made buttons for tkinter

import tkinter as tk
from PIL import Image
import base64
import io
from io import BytesIO


def create_image(w,h, color):
    "Create an image in the memory"
    # create image
    img = Image.new("RGB", (w,h), color)
    # Saves the new image in memory, not on drive
    memfile = BytesIO()
    img.save(memfile, format="PNG")
    # do not need file argument, as it's an image in the memory
    img = tk.PhotoImage(memfile)


def p_print(x):
    print(x)



def button(w, h, text, color, command):

    # Call to make an image in the memory
    img = create_image(w, h, color)
    # create button
    but = tk.Button(
        root,
        bd=1,
        # relief="groove",
        compound=tk.CENTER,
        bg=color,
        fg="yellow",
        activeforeground="gold",
        activebackground="blue",
        font="arial 20",
        text=text,
        pady=1,
        padx=1,
        image=img,
        command=command,
        width=w
        # width=300
    )
    #but.pack()
    return but



counter = 0
crow = 0
mem1 = ""
mem2 = ""
mop = ""
def setEntry(value):
    global esv
    global mem1
    global mem2
    global mop

    print(value)

    if value == "C":
        esv.set("")
    else:
        v = esv.get()
        v += value
        esv.set(v)

        # when you press this... you must put the value in mem1
        # but you must not add other values
        if value in "+-x:":
            mop = value
            print("mop", mop)
            mem1 = v.replace(value, "")
            esv.set("")

        elif value == "=":
            mem2 = v.replace("=","")
            print("mem", mop)
            if mop == "x":
                mop = "*"
            if mop == ":":
                mop = "/"
            result = eval(f"{float(mem1)} {mop} {float(mem2)}")
            esv.set(result)
            mem1 = result
        # Here is when user digit a number
        else:
            # it is the first number, mem it and show it
            if mem1 == "":
                mem1 = value
                esv.set(value)
            # the second number show the first and the second, memorize it
            elif mop == "":
                value = str(mem1) + value
                mem1 = value
                esv.set(value)
            if mem1 == mem2:
                value = str(mem2) + value
                mem2 = value
                esv.set(value)




def Button(text):
    global counter
    global crow
    global entry
    global esv

    # b = button(1, 10, text, "red", None)
    b = tk.Button(root, text=text)
    b["bg"] = "red"
    b["fg"] = "white"
    b["font"] = "arial 20"
    # root.columnconfigure(counter, weight=1)
    # root.rowconfigure(crow, weight=1)
    b["command"] = lambda: setEntry(b["text"])
    if b["text"] in "-+:x":
        b["bg"] = "darkred"
    if b["text"] in "C":
        b["bg"] = "yellow"
        b["fg"] = "green"
    if b["text"] == "=":
        b["bg"] = "green"
        b.grid(row=1+crow, column=counter, columnspan=3, sticky="nswe",ipady=0, ipadx=0)
    else:
        b.grid(row=1+crow, column=counter, sticky="nswe",ipady=0, ipadx=0)
    counter += 1
    if counter > 2:
        crow +=1
        counter = 0
    return b


def main():
    global root
    global esv

    root = tk.Tk()
    root.title("CalpPy")
    root.resizable(False, False)
    esv = tk.StringVar()
    entry = tk.Entry(root, textvariable=esv, justify="right", width=15)
    entry["font"] = "arial 20"
    entry["bg"] = "cyan"
    entry.grid(row=0, column=0, columnspan=3, sticky="nswe")

    # Buttons

    for but in [7, 8, 9, 4, 5, 6,
                1, 2, 3, 0, "+", "-",
                "C", "x", ":", "="]:
        b = Button(str(but))

    root.mainloop()

main()


 


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.