Categories: Python GUI

Start Python GUI Programming with 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.

Related Post

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

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

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. 😁

Aditya Kumar

Share
Tags: Programming Python Python GUI

Recent Posts

  • Programming

Mastering Print Formatting in Python: A Comprehensive Guide

In Python, the print() function is a fundamental tool for displaying output. While printing simple…

8 months ago
  • Programming

Global Variables in Python: Understanding Usage and Best Practices

Python is a versatile programming language known for its simplicity and flexibility. When working on…

8 months ago
  • Programming

Secure Your Documents: Encrypting PDF Files Using Python

PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…

8 months ago
  • Programming

Creating and Modifying PDF Files in Python: A Comprehensive Guide with Code Examples

PDF (Portable Document Format) files are widely used for document exchange due to their consistent…

8 months ago
  • Programming

Boosting Python Performance with Cython: Optimizing Prime Number Detection

Python is a high-level programming language known for its simplicity and ease of use. However,…

8 months ago
  • Programming

Using OOP, Iterator, Generator, and Closure in Python to implement common design patterns

Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…

8 months ago

This website uses cookies.