954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Tiny Tkinter Calculator (Python)

By vegaseat on Dec 9th, 2006 12:37 am

Just a relatively simple calculator using the Tkinter GUI. It has a few nice features such as correcting division by an integer (for older Python versions), error trapping, to and from memory buttons, and an editable display. The editable display allows you to backspace mistakes, and also to enter things not on the key pad, like hexnumbers. For instance if you enter 0xFF and press equals, it will give you the decimal (denary) equivalent of 255

The program also has a guard against the bad guys that like to abuse the underlying eval() function to wipe out files.

I wrote the code in detail, so you can hopefully figure it out. You can fancy up the calculator quite a bit, just experiment with the code.

# a tiny/simple Tkinter calculator (improved v.1.1)
# if you enter a number with a leading zero it will be an octal number!
# eg. 012 would be a decimal 10  (0.12 will not be affected)
# used a more modern import to give Tkinter items a namespace
# tested with Python24     vegaseat     08dec2006

"""
calculator has a layout like this ...
<   display   >
7  8  9  *  C
4  5  6  /  M->
1  2  3  -  ->M
0  .  =  +  neg
"""

import Tkinter as tk

def click(key):
    global memory
    if key == '=':
        # avoid division by integer
        if '/' in entry.get() and '.' not in entry.get():
            entry.insert(tk.END, ".0")
        # guard against the bad guys abusing eval()
        str1 = "-+0123456789."
        if entry.get()[0] not in str1:
            entry.insert(tk.END, "first char not in " + str1)
        # here comes the calculation part
        try:
            result = eval(entry.get())
            entry.insert(tk.END, " = " + str(result))
        except:
            entry.insert(tk.END, "--> Error!")
    elif key == 'C':
        entry.delete(0, tk.END)  # clear entry
    elif key == '->M':
        memory = entry.get()
        # extract the result
        if '=' in memory:
            ix = memory.find('=')
            memory = memory[ix+2:]
        root.title('M=' + memory)
    elif key == 'M->':
        entry.insert(tk.END, memory)
    elif key == 'neg':
        if '=' in entry.get():
            entry.delete(0, tk.END)
        try:
            if entry.get()[0] == '-':
                entry.delete(0)
            else:
                entry.insert(0, '-')
        except IndexError:
            pass
    else:
        # previous calculation has been done, clear entry
        if '=' in entry.get():
            entry.delete(0, tk.END)
        entry.insert(tk.END, key)

root = tk.Tk()
root.title("Simple Calculator")

btn_list = [
'7',  '8',  '9',  '*',  'C',
'4',  '5',  '6',  '/',  'M->',
'1',  '2',  '3',  '-',  '->M',
'0',  '.',  '=',  '+',  'neg' ]

# create all buttons with a loop
r = 1
c = 0
for b in btn_list:
    rel = 'ridge'
    cmd = lambda x=b: click(x)
    tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c)
    c += 1
    if c > 4:
        c = 0
        r += 1

# use Entry widget for an editable display
entry = tk.Entry(root, width=33, bg="yellow")
entry.grid(row=0, column=0, columnspan=5)

root.mainloop()

Simplified the code by creating all the buttons in a loop. Hope you can still follow the flow.

BTW, this is a tiny calculator using a small footprint and short code. You can add more features, but then it wouldn't be a tiny calculator any longer. So, go ahead and improve it and change it to a scientific calculator.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Would you know how to do that using the Tkinter buttons? Is using self a bad thing when dealing with the buttons.


Editor's note: Sorry, put that into the wrong post!
BTW, this is a tiny calculator using a small footprint and short code. You can add more features, but then it wouldn't be a tiny calculator any longer. So, go ahead and improve it and change it to a scientific calculator.

pythonNerd159
Light Poster
30 posts since Mar 2010
Reputation Points: 6
Solved Threads: 2
 

Of course it could be considered user responsibility, but I do not personally like that the calculator does not allow to continue from result and saves formula to memory instead of evaluating the result automatically.

For example:
10/3 M-> = result: 3.333333
* M<- =
result: *10/3.0first char not in -+0123456789.--> Error!

1/3=*3
result: *3first char not in -+0123456789.--> Error!

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

how would you insert square root calculation in this program? I am trying
elif key == 'sqrt':
a = eval(entry.get())
entry.insert(tk.END, "=" + str(math.sqrt(a))
but of cours it's not working. Any ideas, please?

alessiobat
Newbie Poster
2 posts since Jun 2011
Reputation Points: 10
Solved Threads: 0
 

Ah, the power of the eval() function. With this tiny calculator you can easily find the square-root as long as you remember that the square-root of x is simply x to the power 1/2.

So, to find the square-root of 2 simply enter 2**0.5=

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

elif key == 'sqrt':
result = math.sqrt(eval(entry.get()))
entry.insert(END,"√= "+str(result))
this is it. it works for sqrt.

alessiobat
Newbie Poster
2 posts since Jun 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You