Python GUI calc

Python GUI experiment. Simple calculator application made with Tk.
It’s a first choice because it’s integrated into Python, simple to use and powerful enough for most cases. It’s also cross platform like an interpreter.
However, there are many other libraries for GUI:
http://wiki.python.org/moin/GuiProgramming

#!/usr/bin/python

# Python GUI calculator 
# (C) 2011 - netquote.it
# Original code by Emanuele Chiabrera
# Enhanced by Toropov Ivan 

from Tkinter import *

# button text list
cmdlst = ['7', '8', '9', '+', '%',
          '4', '5', '6', '-', '**',
          '1', '2', '3', '*', '//',
          '.', '0', 'CL', '/', '=']

class MyButton(Button):
    
    backref = None
    
    def Click(self):
        # back reference
        self.backref.BtnCmd(self["text"])


class CalcApp:

    def __init__(self, master):
        frame = Frame(master)
        
        self.textbox = Entry(width=30, takefocus=1)
        self.textbox.pack(side=TOP)
        self.textbox.focus_force()

        self.buttons = []
        for n, c in enumerate(cmdlst):
            self.buttons.append(MyButton(frame, text=c, width=5))
            self.buttons[n]["command"] = self.buttons[n].Click
            self.buttons[n].backref = self
            self.buttons[n].grid(row=n/5, column=n%5)

        frame.pack()

    def BtnCmd(self, cmd):
        if cmd == '=':
            try:
                res = eval(self.textbox.get())
            except:
                res = "Error!"
            self.textbox.delete(0, END)
            self.textbox.insert(0, str(res))
        elif cmd == 'CL':
            self.textbox.delete(0, END)
        else:
            self.textbox.insert(END, cmd)

root = Tk()
root.title("EWCalc")

calcapp = CalcApp(root)
root.mainloop()

What comes out:

This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published.