# Hello, Python! print(“Xcalc”) with TKinter GUI Module

Unlike most programmers, Python (which is highly recommended as a first language) wasn’t my first programming language. I started system programming with C++ in 2015, didn’t have much of a choice then as C++ was part of my first semester curriculum. Further back in 2013, I already caught a glimpse of PHP scripting language. As you can imagine, the idea of going beyond print “Hello, World!” in Python2 has always been there and was long overdue by the time I finished college.

Completing my college degree (officially) 2 months ago meant I have extra time in hand to try something new. Viz., Python!

I am already grounded with the concept of object oriented programming; I am no stranger to system programming languages like Java & C++, have expert skill set in PHP server scripting language. Indeed, it wouldn’t hurt to add another programming language to my CV.

### Python should be easy,

Or so I thought. After 9 days of learning Python syntax (or unlearning the use of commas & braces), loops, function, classes, modules and GUI (TK), I must have felt that I have arrived at the very pinnacle of Python programming language. I wasted no time in taking the LinkedIn quiz intent on displaying my shinning new programming skill on my LinkedIn profile. As you must have guessed by now, I wasted no time in failing the LinkedIn quiz.

Not a very good start, some might say. However, there were lots of positives. One of them is

### My very own first Python GUI program, Xcalc

As the program description in Help > About clearly states:

Simple Calculator (xcalc) is a vanity Python project by Ebenezer Obasi (www.eobasi.com). It should enable you do basic calculation such as addition, subtraction, multiplication and division, but should it fail, just know it’s my first Python GUI program.

Unlike most programming languages, leaning the basics of Python is unbelievably easy if you are new to programming in general. However, if you are coming from a different programming background like Java and C++, it becomes a bit tricky to unlearn your old habit of ending a line a with semi-colon. If this your case, I should warn you ahead:

• In Python, new line indicates the end of the preceding statement. Commas may be used but only to separate statements on the same line.
"""Code to calculate Simple Interest in Python3"""
#statements on each line; notice that semi-colon is not used
P = 1000
r = 3.82
t = 7
A = P * (1 + r * t)
print(A)

#statements in one line; notice the use of semi-colons
P = 1000; r = 3.82; t = 7; A=P*(1+r*t);print(A)

• Python used indentation in place of curly braces used in Java and C++ block statements.

#### C++ Function

//create a function in C++
int main(){
cout << "Hello, World!" << endl;
return 0;
}


#### Python Function

#create a function in Python
def main():
print("Hello, World!")
return

#call the function
main()

• Python is a loosely type programming language. Meaning you don’t have to define a data type when you initialize a variable or function.
• Pay heavy attention to indentation. Python relies on indentation for more than just clean codes.

Notwithstanding, Python has a smooth learning curve, regardless on your programming stand. In fact, some of the principal ideas behind Python include:

• Simple is better than complex.
• Beautiful is better than ugly.
• Special cases aren’t special enough to break the rules.
• If the implementation is hard to explain, it’s a bad idea.
• If the implementation is easy to explain, it may be a good idea.
• More from The Zen of Python.

Python comes with a lot of very useful libraries and modules that can make your job a lot easier. The Xcalc GUI program for instance, was written with Python3 TK GUI toolkit. It took only 168 line of codes to produce the Xcalc program.

#### Xcalc Source Code

#!/usr/bin/python3
import tkinter
import tkinter.messagebox

WIN_WIDTH = 360
WIN_HEIGHT = 420

NUM_COLUMN_COUNT = 3
OPERATOR_COLUMN_COUNT = 3

BTN_WIDTH = 4
BTN_HEIGTH = 3
BTN_FONT = ("Arial", 14)

DISPLAY_HEIGHT = 3
DISPLAY_WIDTH = 20
DISPLAY_FONT = ("Arial", 18)
DISPLAY_SM_FONT = ("Arial", 14)

DISPLAY_CHAR_LIMIT = 20

numpad = [1,2,3,4,5,6,7,8,9,0, '.']
operators = ['+','-', '/', '*', '=']

box = tkinter.Tk()

def winDocument( params = {}):
winParams = {
"title": "Document::Simple Calculator",
"content": "",
"minwidth": 400,
"minheight": 400,
}
winParams.update(params)
winDocument = tkinter.Toplevel(box)
winDocument.title(winParams["title"])
winDocument.minsize(width=winParams["minwidth"], height=winParams["minheight"])

content = tkinter.Message(winDocument, text=winParams["content"], background="#2f4f68", foreground="#fff", font=("Arial", 14))
content.pack(expand=1,fill=tkinter.BOTH)

"content": "Simple Calculator (xcalc) is a vanity python project by Ebenezer Obasi (www.eobasi.com). It should enable you do basic calculation such as addition, substraction, multiplication and division, but should it fail, just know it's my first Python GUI program.\
\n\nTips:\n - Use ** operator to get the power of a number.\n- Use // operator to get the floor of numbers divided.\
\n\nFeel free to contact me anytime at info@eobasi.com"
}), background="#2f4f68", foreground="#fff", font=("Arial", 14))

def btnCallBack(x):
if str(x) == '=':
try:
calc = eval(equation.get())
except:
equation.set('error')
else:
equation.set(str(calc))
return
elif str(x) == 'clear':
equation.set("")
return
elif str(x) == 'c':
e = str(equation.get())
e = e[:-1]
equation.set(e)
else:
equation.set(equation.get()+str(x))

def generateBtn(master, label, grid = {}, params = {}):
btnParams = {
"text": label,
"bg": "#2f4f68",
"bd": 0,
"font": BTN_FONT,
"fg": "#fff",
"relief":"sunken",
"activebackground": "#324e64",
"activeforeground": "#fff",
"width": BTN_WIDTH,
"height": BTN_HEIGTH,
"command": lambda: btnCallBack(label)
}
btnParams.update(params)

btn = tkinter.Button(master, btnParams)
btn.grid(grid)

box.configure(background = "#3c4248")
box.title("Simple Calculator")
box.geometry("{}x{}".format(WIN_WIDTH, WIN_HEIGHT))
box.minsize(width=WIN_WIDTH, height=WIN_HEIGHT)
box.maxsize(width=WIN_WIDTH, height=WIN_HEIGHT)

dispalyArea = tkinter.Frame(box, bg="#333")
dispalyArea.grid(columnspan = 2, row = 0, column = 0)

numArea = tkinter.Frame(box, bg="#201c29")
numArea.grid( row = 1, column = 0, ipady="20")

operatorArea = tkinter.Frame(box, bg="#201c29")
operatorArea.grid( row = 1, column = 1, ipady="20")

equation = tkinter.StringVar()

display = tkinter.Entry(dispalyArea, {
"textvariable": equation,
'bg': "#333",
"fg": "#fff",
'bd': 0,
#'wraplength':20,
#'anchor': "w",
"font":DISPLAY_FONT,
"width":DISPLAY_WIDTH,
})

column = row = count = 0

for x in range(0, len(numpad)):
params = {}
grid = {"column":column, "row":row}

if x == (len(numpad) - 1) and column < (NUM_COLUMN_COUNT - 1):
grid.update({"columnspan":(NUM_COLUMN_COUNT - 1)})
params.update({"width":BTN_WIDTH*3})

generateBtn(numArea, label=numpad[x], grid=grid, params=params)

if count == (NUM_COLUMN_COUNT - 1):
row += 1
column = 0
count = 0
else:
count += 1
column += 1

generateBtn(operatorArea, label='c', grid={ "column":0, "row":0, "columnspan":2}, params={"width":BTN_WIDTH*3})

row = 1; column = count = 0
for x in range(0, len(operators)):
params = {}
grid = {"column":column, "row":row}

if x == (len(operators) - 1) and len(operators) % 2 == 1:
if column < 1:
grid.update({"columnspan":2})
params.update({"width":BTN_WIDTH*3})

generateBtn(operatorArea, label=operators[x], grid=grid, params=params)

if count == 1:
row += 1
column = 0
count = 0
else:
count += 1
column += 1

generateBtn(dispalyArea, label='clear', grid={ "column":3, "row":0, "columnspan":1})

box.mainloop()


## Xcalc Structure

### Did you get the answer you were searching for?

Save hours of searching online or wasting money testing unnecessary plugins, get in touch with me and let's discuss a suitable plan for your project. Best thing about this service is that you are never placed on hold and get to talk to an expereinced Oxwall/Skadate developer.

Ask a question related to this topic and get immediate answers from other community members in 48hrs or less. Contribute by answering members questions.