Top 10 Programming Languages to Learn in 2019

Python GUI

Start Python GUI Programming with Tkinter

start-python-gui tkinter

In this tutorial, you will learn about Python GUI Programming with Tkinter module and be able to develop Basic Python Applications like Calculators. I would like you to code along so that you will get better understanding of the tutorial.

I have divided this tutorial in two sub parts:

  • Hello World Application
  • Basic Calculator Application

The first part contains all the basic info. I assume that you have some you’re already somewhat familiar with Python Programming Language. Additionally, you need to know about Object Oriented Programming. In case you are unfamiliar with Python, I highly recommend you to go through our Introduction to Python Programming Tutorial.

Introduction to python programming

What is Tkinter?

Tkinter provides Python applications with an easy to program interface. Tkinter supports a collection of Tk widgets that supports most applications needs. Tkinter in python is the interface to Tk, GUI tool kit for Tcl/Tk. Tkinter comprises a number of components. _tkinter is the low-level interface to Tk libraries and is linked into Python.

From the Python release 1.5.2 Tkinter, Tk and Tcl are the part of the standard installation package.

Tkinter Features

Tkinter adds object oriented features to Tcl/Tk. We use the Tk widgets to apply an operation to a widget identifier as Tkinter refers widgets as objects and you can drive the functions of the widgets using object methods and their attributes.

Tkinter Major widgets

These are some of the major Tkinter widgets which you will use frequently.

  1. Button
  2. Canvas
  3. Check Button
  4. Frame
  5. Label
  6. Listbox
  7. Menu
  8. Message
  9. Scale
  10. Text
  11. Entry
  12. Scroll Bar

Now comes the fun part. Let’s code 😁


Hello World Application

A “Hello world” program is necessary to illustrate the ease with which a language may be applied. So let’s follow the trend and start with it.

from tkinter import mainloop, Label

myLabel = Label(text="Hello World!!\n My first GUI Application.", font=("Arial, 24"), height=10, bg = '#4e148c').pack()

# call the mainloop
mainloop()
tkinter hello world application
Tkinter hello world Application

Code Explanation

  • Firstly we will import all the required components from the Tkinter module using the statement
from tkinter import Label, mainloop
  • We created a Label containing text and use the pack geometry manager to realize the widget using the statement.
myLabel = Label(text="Hello World!!\n My first GUI Application.", font=("Arial, 24"), height=10, bg = '#4e148c').pack()
  • Finally we call the Tkinter mainloop to process events and keep the display activate. We need main loop to keep the program to keep being displayed
mainloop()

Basic Calculator Application

Now let’s go through a good example to boost your understanding of the topic. The example will illustrate you various Python and Tkinter features. The finished application will view somewhat like this:

basic tkinter calculator
Basic Tkinter Calculator

Code Explanation

  • We begin by making some convenience functions to reduce the number of lines of the code. You will certainly appreciate the reduced complexity and size of code resulting from this. Moreover, it also helps while code maintenance.
def frame(root, side):
    w = Frame(root)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

def button(master, side, text, command=None):
    w = Button(master=master, text=text, command=command)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w
  • We then inherit the Frame class in Calculator class. Then we call the Frame constructor to create a top-level shell and an enclosing frame. Then we set the titles and icon names.
class Calculator(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple Calculator')
        self.master.iconname('calculator')

        display = StringVar()
        # Entry Place
        Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH)
  • Now, we create the display at the top of the calculator and define a tkinter variable which provides access to the widget contents and we also declare a Entry widget to collect the user Input.
class Calculator(Frame):
    def __init__(self):
        # ... Upper code snippet is not included ...

        display = StringVar()
        # Entry Place
        Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH)
  • We create Frame with each row of keys. In python, character strings are a sequence of characters in Python. We will use this to make the layout. Then we use our convenience button function to render the buttons.
class Calculator(Frame):
    def __init__(self):
        # ... upper code snippet not included ...

        for key in ('123', '456', '789', '-0.'):
            keyF = frame(self, TOP)
            # lambda w = display
            for char in key:
                # print(char)
                button(keyF, LEFT, char, lambda w = display, c = char:w.set(w.get() + c))
  • The = key has an alternate binding which calls the calc function to do the evaluations and return the results. Then we create a frame and made a clear button which sets the Entry widget to ” “.
class Calculator(Frame):
    def __init__(self):
        # ... upper code snippet not included ...

        opsF = frame(self, TOP)
        for char in '/*-+=':
            if char == '=':
                btn = button(opsF, LEFT, char)
                btn.bind('<ButtonRelease-1>', lambda e, s=self, w=display: s.calc(w), '+')
            else:
                btn = button(opsF, LEFT, char, lambda w = display, c=char:w.set(w.get() +' '+c+' '))

        clearF = frame(self, TOP)
        clear = button(clearF, LEFT, 'Clear', lambda w = display: w.set(''))
  • The last section contains the calc function which collects the string from the display and tries to evaluate it when the left mouse button is released. It then replaces the string in display with the calculated value or ERROR.

Code

from tkinter import *

def frame(root, side):
    w = Frame(root)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

def button(master, side, text, command=None):
    w = Button(master=master, text=text, command=command)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

class Calculator(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Simple Calculator')
        self.master.iconname('calculator')

        display = StringVar()
        # Entry Place
        Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH)

        for key in ('123', '456', '789', '-0.'):
            keyF = frame(self, TOP)
            # lambda w = display
            for char in key:
                # print(char)
                button(keyF, LEFT, char, lambda w = display, c = char:w.set(w.get() + c))

        opsF = frame(self, TOP)
        for char in '/*-+=':
            if char == '=':
                btn = button(opsF, LEFT, char)
                btn.bind('<ButtonRelease-1>', lambda e, s=self, w=display: s.calc(w), '+')
            else:
                btn = button(opsF, LEFT, char, lambda w = display, c=char:w.set(w.get() +' '+c+' '))

        clearF = frame(self, TOP)
        clear = button(clearF, LEFT, 'Clear', lambda w = display: w.set(''))

    def calc(self, display):
        try:
            x = eval(display.get())
            display.set(x)
        except ValueError:
            display.set('Error')

if __name__ == '__main__':
    Calculator().mainloop()

Do like and comment below if you face any issue. I will be happy to help you. 😁

Related posts
PyQt5Python GUI

PyQt5 - Message Box Widget

PyQt5Python GUI

PyQt5 - PushButton

PyQt5Python GUI

PyQt5 - Window Widget

Leave a Reply

Your email address will not be published. Required fields are marked *

Improve Your Python

...with a fresh 🐍 Python Trick 💌
code snippet every couple of days:

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

PyBlog will use the information you provide on this form to be in touch with you and to provide updates and marketing.