Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPython Tkinter Projects [Step-by-Step Explanation]

Python Tkinter Projects [Step-by-Step Explanation]

Last updated:
21st Nov, 2022
Views
Read Time
14 Mins
share image icon
In this article
Chevron in toc
View All
Python Tkinter Projects [Step-by-Step Explanation]

Learning about GUI in Python can be quite challenging. Don’t worry because we have got your back! In this article, we’ve shared a Tkinter tutorial so you can work on Python GUI projects efficiently. After completing this tutorial, you’d be familiar with the building blocks for creating Python Tkinter projects. If you want to gain more expertise in python, checkout our data science programs.

We’ve also shared the code for every step. However, we recommend that you copy and paste it only when you understand how it works. Otherwise, it wouldn’t be of much use. 

What is Tkinter?

Tkinter is a package for Python to use the Tk GUI toolkit. You can use Tkinter for creating GUI programs through Python. While Tkinter is capable of producing many programs, you might need to use modules for advanced implementations. You should be familiar with the basics of Tkinter before working on Python Tkinter projects:

Tkinter Widgets

Tkinter widgets are basically controls such as buttons, text boxes, and labels, that are used in GUI applications. There are as many as 15 types of Tkinter widgets, namely, canvas, label, frame, menu, menubutton, and message, among others.

A Hello World Program in Tkinter

Here’s an example of a hello world program in Tkinter:

import tkinter as tk

class Application(tk.Frame):

    def __init__(self, master=None):

        super().__init__(master)

        self.master = master

        self.pack()

        self.create_widgets()

    def create_widgets(self):

        self.hi_there = tk.Button(self)

        self.hi_there[“text”] = “Hello World\n(click me)”

        self.hi_there[“command”] = self.say_hi

        self.hi_there.pack(side=”top”)

        self.quit = tk.Button(self, text=”QUIT”, fg=”red”,

                              command=self.master.destroy)

        self.quit.pack(side=”bottom”)

    def say_hi(self):

        print(“hi there, everyone!”)

root = tk.Tk()

app = Application(master=root)

app.mainloop()

Geometry Managers in Tkinter

Another main concept you should know about while working on Python Tkinter projects is geometry managers. Without using a geometry manager, your widgets wouldn’t appear on the screen. There are primarily three ways you can add a geometry manager:

Grid

It adds a grid to the parent and allows it to show widgets accordingly. The grid has rows and columns for measuring the length and height of its widgets. 

Pack

This method tells the widget to pack itself within the parent. It only adds the widget to a list of children widgets for the parent. In simple terms, it adds them to a block before it places them in a parent widget. 

Place

This method places widgets in a specific location according to the parent widget. 

In our tutorial below, we have used the pack manager for handling the position of our widgets. That’s why it’d be best if you’re familiar with these concepts. It would help you to understand the working of our project better. 

Checkout: 42 Exciting Python Project Ideas & Topics for Beginners

Building a GUI in Python (Tkinter Tutorial)

Step#1: Importing the Module

To begin working on the application, we first have to import the necessary module. You can do so by importing the module in your namespace. It would allow you to use the constants and classes by their names instead of qualifying them. This means you can use “Label” by using its name instead of qualifying it as “TkinterLabel.” It would make things relatively easy, and you can save a lot of time as qualifying every class and constant can be very cumbersome. Use the following code to import the module:

>>> from Tkinter import *

If Python is not linked to Tk (or Tcl) in your system or if you don’t have Tk (or Tcl) installed in your system, you would see an error message in this section. To fix this issue, you would need your system’s administrator for access. Make sure that you solve this problem by doing the same. 

On the other hand, if you don’t see any error messages in these sections, you can move onto the next step to create a window:

>>> win = Tk()

We’ve assigned our window the variable “win.” After implementing the code above, you would get to see a small window on the screen. Its title bar should show “tk” written in it. 

This means you’ve completed this step successfully and can now start building GUI in Python. 

Read our popular Data Science Articles

upGrad’s Exclusive Data Science Webinar for you –

How to Build Digital & Data Mindset

Explore our Popular Data Science Courses

Step#2: Adding Buttons 

Now that we have our Tkinter running, we can add buttons to our program. Buttons are the simplest section of any GUI program, so we’ll start with them:

>>> b1 = Button(win, text=”One”)

>>> b2 = Button(win, text=”Two”)

The window we created in the last section is the parent for the buttons we made now. As you’ll work on more Python Tkinter projects, you’ll find that frames can also act as parents for other classes. Now, when you implement this code, you would notice a strange occurrence – The buttons don’t appear in the window!

That’s because we need to add a grid and a pack to our program. They are called geometry managers, and we’ve discussed them earlier in this article. We’ll add the pack manager in our next section:

Step#3: Implementing the Pack Manager 

We’ll use the pack method to add our buttons to the parent widget. With the pack manager, you can tell which side of the parent widget you want your child widget to be packed against. You can use TOP, RIGHT, BOTTOM, LEFT as your functions. The program selects TOP as default if you don’t specify a side. Let’s add the pack manager first:

>>> b1.pack()

>>> b2.pack()

When you add the first button (first line of the code), you will notice that your window shrinks to the button’s size. Similarly, when you add the second button (second line of the code), the window expands according to that button’s size. The window has placed the buttons in vertical order because we didn’t specify which side they should be packed against. Let’s pack them on the left by using the code below:

>>> b2.pack(side=LEFT)

>>> b1.pack(side=LEFT)

Note that we use the pack manager mostly when we have to place our widgets in these two orders (horizontal and vertical) only. For other types of widget placements, we use the grid method or the place method. You can add some space between the buttons and the window using the ‘padx’ or ‘pady’ functions. The ‘padx’ function adds padding to the X-axis (left and right) of the widget, and the ‘pady’ function adds padding to the Y-axis (top and bottom) of the device. 

>>> b1.pack(side=LEFT, padx=10)

>>> b2.pack(side=LEFT, padx=10)

We recommend experimenting with the padding of the widgets. It would help you in understanding the different ways you can modify the placement of widgets. Padding is a challenging concept to master, so it would be best to try it out before you move onto the next section. 

Also, Check out all trending Python tutorial concepts in 2024.

Step#4: The Grid Manager 

Another popular geometry manager in Tkinter is the grid manager. As we’ve discussed earlier in our article, the grid manager allows you to divide the parent into rows and columns. You can place the child widgets in the cells of the parent’s grid. You can modify the width and length of every column and row according to your requirements. Not every column has to be of the same width. Similarly, every row doesn’t need to have the same height. So, the grid manager gives you more creative liberty in terms of editing your widgets’ appearance and placement. 

We’ll create a new window with the same buttons we created before to test out the grid manager. However, we’ll add the buttons in a 2×2 grid:

>>> win = Tk()

>>> b1 = Button(win, text=”One”)

>>> b2 = Button(win,text=”Two”)

>>> b1.grid(row=0, column=0)

>>> b2.grid(row=1, column=1)

You’d notice that our program has left some cells empty. That’s because we didn’t add anything to row 0, column 1 (or row 1 and column 0). We will try a new widget to see something interesting:

>>> l = Label(win, text=”This is a label”)

>>> l.grid(row=1, column=0)

Once you add the above code, you notice that the second button shifts to the right to accommodate the text. It would be best to try out the grid manager with multiple widgets to see how it functions. 

Must Read: Django Developer Salary in India

Top Data Science Skills to Learn

Step#5: Improving the Layout

In this section we’ll try a new widget called frame. A frame is only for containing other widgets. You can pack multiple widgets into a frame or use a grid to place them in the same. You can also pack different frames into a single frame. This feature allows you to create advanced layouts for your GUI program. For example, we’ll add three buttons to a frame in a row. Add the buttons horizontally and then pack the label vertically with the frame:

>>> win = Tk()

>>> f = Frame(win)

>>> b1 = Button(f, “One”)

>>> b2 = Button(f, “Two”)

>>> b3 = Button(f, “Three”)

>>> b1.pack(side=LEFT)

>>> b2.pack(side=LEFT)

>>> b3.pack(side=LEFT)

>>> l = Label(win,”This label is over all buttons”)

>>> l.pack()

>>> f.pack()

As we have discussed earlier in the article, you can also use the place method as the geometry manager. The place method allows you to put widgets in a specific location within a window or a frame. However, we don’t recommend using the place method frequently because it restricts the program’s responsiveness. 

With the grid function, you can use the ‘sticky’ parameter that allows you to use map coordinates (S, N, W, SW, NE, etc.) for specifying widget placements. Before we move onto the next section, make sure that you understand the functions we’ve discussed yet. Test out the grid, and the frame functions together to see how you can use it in other Python GUI projects. 

Step#6: Making the Buttons Useful

If you’d click the buttons we’ve created so far, you must have noticed that they are unresponsive (they don’t do anything). They depress when you click and highlight when you hover above them, but they don’t perform any functions. To make our buttons perform specific functions, we’ll have to use the ‘configure’ function. 

We can pass any keyword argument to a widget’s ‘configure’ method to pass it while creating it. Here’s an example:

>>> b1.configure(text=”Uno”)

The ‘command’ parameter ties the buttons to callback functions when you create them or add ‘configure’ to them. To understand how it works, we’ll create a function that prints out a message:

>>> def but1():

… print(“Button one was pushed”)

>>> b1.configure(command=but1)

So when you’d click the respective button, it would print a message. 

Step#7: Adding Entry Widgets

Entry widgets allow users to enter text into the program. However, we would have to make the entry widget functional as we did with the buttons. An entry widget has to retrieve (and set) text. For the entry widget to perform this function, you’d have to use the Tkinter object ‘StringVar.’ The ‘StringVar’ object holds the text in the form of a string and makes it readable through get. 

We’ll create a new window to test our entry widgets:

>>> win = Tk()

>>> v = StringVar()

>>> e = Entry(win,textvariable=v)

>>> e.pack()

Let’s now add “this is a test” as the entry and retrieve the same through StringVar:

>>> v.get()

“this is a test”

You can now set the text into StringVar and make it appear in the widget:

>>> v.set(“this is set from the program”)

Additional Widget: The Listbox Widget

Apart from the entry widget, we can add a listbox widget. A listbox widget lets the user choose an item from a menu. We’ll create a new window to try out the listbox widget:

>>> win = Tk()

>>> lb = Listbox(win, height=3)

>>> lb.pack()

>>> lb.insert(END, “first entry”)

>>> lb.insert(END, “second entry”)

>>> lb.insert(END, “third entry”)

>>> lb.insert(END, “fourth entry”)

You can insert items at the beginning, the middle, and the end of the list. You can delete them too. If there are too many items on the list, you can add a scrollbar:

>>> sb = Scrollbar(win, orient=VERTICAL)

>>> sb.pack(side=LEFT, fill=Y)

To make our scrollbar functional we’ll have to use call back functions:

>>> sb.configure(command=lb.yview)

>>> lb.configure(yscrollcommand=sb.set)

The curselection method returns an item to you when you select it in the list box. It will return an empty tuple if you don’t choose any items. 

Step#8: Final Steps

We’ll use all the stuff we learned in our Tkinter tutorial to create a phone list editor:

Total Code

#!/usr/bin/env python3

from tkinter import *

from phones import *

def which_selected():

    print(“At {0}”.format(select.curselection()))

    return int(select.curselection()[0])

def add_entry():

    phonelist.append([fnamevar.get(), lnamevar.get(), phonevar.get()])

    set_select()

def update_entry():

    phonelist[which_selected()] = [fnamevar.get(),

                                   lnamevar.get(),

                                   phonevar.get()]

def delete_entry():

    del phonelist[which_selected()]

    set_select()

def load_entry():

    fname, lname, phone = phonelist[which_selected()]

    fnamevar.set(fname)

    lnamevar.set(lname)

    phonevar.set(phone)

def make_window():

    global fnamevar, lnamevar, phonevar, select

    win = Tk()

    frame1 = Frame(win)

    frame1.pack()

    Label(frame1, text=”First Name”).grid(row=0, column=0, sticky=W)

    fnamevar = StringVar()

    fname = Entry(frame1, textvariable=fnamevar)

    fname.grid(row=0, column=1, sticky=W)

    Label(frame1, text=”Last Name”).grid(row=1, column=0, sticky=W)

    lnamevar = StringVar()

    lname = Entry(frame1, textvariable=lnamevar)

    lname.grid(row=1, column=1, sticky=W)

    Label(frame1, text=”Phone”).grid(row=2, column=0, sticky=W)

    phonevar = StringVar()

    phone = Entry(frame1, textvariable=phonevar)

    phone.grid(row=2, column=1, sticky=W)

    frame2 = Frame(win) # Row of buttons

    frame2.pack()

    b1 = Button(frame2, text=” Add “, command=add_entry)

    b2 = Button(frame2, text=”Update”, command=update_entry)

    b3 = Button(frame2, text=”Delete”, command=delete_entry)

    b4 = Button(frame2, text=”Load “, command=load_entry)

    b5 = Button(frame2, text=”Refresh”, command=set_select)

    b1.pack(side=LEFT)

    b2.pack(side=LEFT)

    b3.pack(side=LEFT)

    b4.pack(side=LEFT)

    b5.pack(side=LEFT)

    frame3 = Frame(win) # select of names

    frame3.pack()

    scroll = Scrollbar(frame3, orient=VERTICAL)

    select = Listbox(frame3, yscrollcommand=scroll.set, height=6)

    scroll.config(command=select.yview)

    scroll.pack(side=RIGHT, fill=Y)

    select.pack(side=LEFT, fill=BOTH, expand=1)

    return win

def set_select():

    phonelist.sort(key=lambda record: record[1])

    select.delete(0, END)

    for fname, lname, phone in phonelist:

        select.insert(END, “{0}, {1}”.format(lname, fname))

win = make_window()

set_select()

win.mainloop()

Here is the phone list:

phonelist = [[‘Chris’, ‘Meyers’, ‘241-343-4349’],

             [‘Robert’, ‘Smith’, ‘202-689-1234’],

             [‘Janet’, ‘Jones’, ‘609-483-5432’],

             [‘Ralph’, ‘Barnhart’, ‘215-683-2341’],

             [‘Eric’, ‘Nelson’, ‘571-485-2689’],

             [‘Ford’, ‘Prefect’, ‘703-987-6543’],

             [‘Mary’, ‘Zigler’, ‘812-567-8901’],

             [‘Bob’, ‘Smith’, ‘856-689-1234’]]

The program we shared here is an example. You can create your program with the functions we discussed in this Tkinter tutorial. The above program lacks several functionalities, such as it doesn’t have the option to save any changes. You can add the save function by yourself by creating a button that can perform this task. 

Must Read: Markov Chain in Python Tutorial

Advantages of Tkinter Module In Python

Now that you have a basic understanding of what exactly Python Tkinter refers to, and how it operates, let’s take a look at some of the basic advantages of the Tkinter module in Python that are mentioned below.

  • When compared with other GUI toolkits, Tkinter is much easier and faster to use.
  • You no longer need to download anything extra, since Tkinter is already included in Python.
  • Tkinter has a simple syntax, as well as three geometry managers, namely grid, place, and pack. 
  • Last but not least, Python Tkinter is also extremely easy to understand, and can be mastered quite easily.

What is Python GUI Programming?

GUI, also known as Graphical User Interfaces, are computer programs that enable users to make use of visuals in order to interact with underlying systems. A basic example of the same might include our mobile phones, which are equipped with such GUIs that help us to interact with various functionalities through tap, touch, or display. Similarly, Python GUI is a graphical user interface that is written in this programming language. As we all know, Python, by far, is considered to be one the most popular programming languages due to its several benefits, such as easy readability, and beginner friendliness, among others. Furthermore, this programming language is also equipped with various frameworks that make it great for developing a graphical user interface. 

Python GUI Programming Use Cases

Mobile Applications- Instagram, Reddit, and Pinterest are some of the best examples of mobile applications that make use of Python GUI. 

Games- Several gaming applications, such as Flappy Bird or Mount & Blade, also make use of Python GUI in order to provide a better user experience, such as flashy graphics, and rewarding interactivity. 

Human-Machine Interfaces- Last but not least, human-machine interfaces are present across various industries. Human-machine interfaces, also known as HMI, are basically graphic user interfaces that are responsible for providing an overview of industrial monitoring and control systems. Furthermore, this also includes providing appropriate solutions in case of any anomalies in the operating system. Python makes the development of these industrial applications much easier and at a reduced cost, which is one of the most important requirements of all businesses. 

Learn More About Python and Python GUI Projects    

Working on Python Tkinter projects can be pretty fun if you know what you’re doing. They are also a great way to understand your strong (and the weak) points. You can learn more about Python; we recommend heading to our blog. Here are some resources for further reading:

What are your thoughts on this project? Have you worked on other Python Tkinter projects? Let us know. 

If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1Is Python suitable for creating graphical user interfaces?

Python has a number of graphical user interface frameworks, ranging from Tkinter to a number of other cross-platform solutions, as well as platform-specific bindings. Creating graphical user interfaces is quick and easy when Python is combined with Tkinter. Python is ideal for GUI creation because it has a lot of built-in widgets, it generates windows quickly, has strong event handling techniques, and has rudimentary drawing capabilities.

2Tkinter or KIVY: which is better to use?

Kivy is a free and open-source Python framework for creating or designing unique but appealing user interface programmes. If you're a python developer who enjoys creating apps, KIVY is an excellent choice for creating more dynamic applications. Tkinter is the most widely used Python interface for developing GUI applications quickly and easily. If you're new to Python and want to learn how to create computer interfaces, start with Tkinter and learn the fundamentals.

3What are some of the drawbacks of using Tkinter Python?

Advanced widgets are not included in Tkinter. It doesn’t have a tool like Qt Designer for Tkinter. It doesn’t have a dependable user interface. Tkinter can be difficult to debug at times. It lacks a native appearance and feel. Tkinter can be useful for creating simple and quick GUIs for Python scripts, but for more complex programming output, almost all programmers prefer the PyQt capabilities.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905253
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20923
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5068
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5178
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17645
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10803
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80763
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
139122
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon