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

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. 

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. 

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

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. 

Get our free whitepaper!
Data Science in Healthcare
the next biggest thing
Download Now

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

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 PG Diploma 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.

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN DATA SCIENCE
Enroll Today

Leave a comment

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

×
Download Whitepaper
Download Whitepaper
By clicking Download Whitepaper, you agree to our terms and conditions and our privacy policy.
Get our free whitepaper!
Data Science in Healthcare
the next biggest thing
Download Now
Aspire to be a Data Scientist
Download syllabus & join our Data Science Program and develop practical knowledge & skills.
Download syllabus
By clicking Download syllabus, I authorize upGrad and its representatives to contact me
via SMS / Email / Phone / WhatsApp / any other modes.
I agree to upGrad terms and conditions and our privacy policy.