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

Simple Calculator (Xcalc) Python Program

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)

#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!")

#call the function
  • 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.
  • Readability counts.
  • 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

import tkinter
import tkinter.messagebox



BTN_FONT = ("Arial", 14)

DISPLAY_FONT = ("Arial", 18)
DISPLAY_SM_FONT = ("Arial", 14)


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,
    winDocument = tkinter.Toplevel(box)
    winDocument.minsize(width=winParams["minwidth"], height=winParams["minheight"])

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

def menubar():
    menubar = tkinter.Menu(box)

    helpmenu = tkinter.Menu(menubar, tearoff=0)
    helpmenu.add_command(label="About...", command=lambda: winDocument(params={
        "title": "About...",
        "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 [email protected]"
    }), background="#2f4f68", foreground="#fff", font=("Arial", 14))
    menubar.add_cascade(label="Help", menu=helpmenu)

    return menubar

def btnCallBack(x):
    if str(x) == '=':
            calc = eval(equation.get())
    elif str(x) == 'clear':
    elif str(x) == 'c':
        e = str(equation.get())
        e = e[:-1]

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

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,
    #'anchor': "w",
display.grid(columnspan=3,row = 0, ipadx=10, column=0, padx="5")

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)})

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

    if count == (NUM_COLUMN_COUNT - 1):
        row += 1
        column = 0
        count = 0
        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:

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

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

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


You can download Xcalc full source code from Github >> https://github.com/eobasi/xcalc

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.

Get Answers for Free!

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

Ask Question
Premium Service

Whether it's a custom plugin, theme or dedicated support needed to get you started on your project, get professional 24/7 support tailored to your need.

Get in Touch

Or just leave a comment...

Post Tags:

  • https://www eobasi com/first-python-gui-progam-xcalc/
  • https://www eobasi com/contact/\ class=\btn btn-primary btn-sm\>Get in Touch</a></div></div></div></div><p class=\card-text\ style=\margin-top:25px;\><small class=\text-muted\>Or just <a href=\#comments\>
  • https://www eobasi com/first-python-gui-progam-xcalc/?share=email

Leave a Reply