how to store number to calculate in tkinter

48 Views Asked by At

I've been trying to create a calculator using tkinter but I got a problem in storing numbers so that I can calculate using operators.I tried to store the value in number but when I press the = key the value of number changes as well. Can someone help with it?

from tkinter import *
import utils

display = Entry(window, borderwidth=10, bg='#EDF1D6', font='bold5')
display.place(x=0, y=0, width=utils.width_prct(75), height=utils.height_prct(15))

def btn_press(btn):
    current = display.get()
    display.delete(0, END)
    display.insert(0, (str(current) + str(btn)))


operators = ['C', 'x', '/', '+', '-', '=', '^']
def opt_press(btn1):
    number = display.get()
    num = int(number)
    display.delete(0, END)
    if btn1 != operators[5]:
        if btn1 == operators[0]:
            display.delete(0, END)
        elif btn1 == operators[1]:
            display.delete(0, END)
            num *= num
        else:
            current1 = display.get()
            display.delete(0, END)
            display.insert(0, (str(current1) + str(btn1)))
            display.delete(0)
    else:
        print(num)
        display.insert(0, num)




for i in range(0, 10):
    btn = Button(window, text=i, bg='#9DC08B', fg='black', font='bold5', command=lambda i = i: btn_press(i))
    if i == 7:
        btn.place(x=0, y=utils.height_prct(15), width=utils.width_prct(25), height=utils.height_prct(20))
    if i == 4:
        btn.place(x=0, y=utils.height_prct(35), width=utils.width_prct(25), height=utils.height_prct(20))
    if i == 1:
        btn.place(x=0, y=utils.height_prct(55), width=utils.width_prct(25), height=utils.height_prct(20))


for o in operators:
    btn_o = Button(window, text=o, bg='#609966', fg='black', font='bold5', command=lambda o=o : opt_press(o))
    if o == 'C':
        btn_o.place(x=utils.width_prct(75), y=0, width=utils.width_prct(25), height=utils.height_prct(15))
    if o == operators[1]:
        btn_o.place(x=utils.width_prct(75), y=utils.height_prct(15), width=utils.width_prct(25),
                    height=utils.height_prct(20))


window.mainloop()
1

There are 1 best solutions below

0
NULL On

You can store a variable/value outside the function you call every time you press the operator button so the variable doesn't reset each time.

now num is a global variable and will keep its value.

num = 0
def opt_press(btn1):
    global num
    if num == 0:
        num = int(display.get())
    display.delete(0, END)
    if btn1 != operators[5]:
        if btn1 == operators[0]:
            display.delete(0, END)
            num = 0
        elif btn1 == operators[1]:
            display.delete(0, END)
            num *= num 
        else:
            current1 = display.get()
            display.delete(0, END)
            display.insert(0, (str(current1) + str(btn1)))
            display.delete(0)
    else:
        print(num)
        display.insert(0, num)