GUIs for Python — A Introduction to Tkinter

A brief overview covering the basics of Tkinter, python’s standard GUI library, and how to build a basic GUI.

James Denbow
Oct 5, 2020 · 10 min read

Overview

Tk is an open-source, cross-platform widget toolkit that allows for developers to create basic GUIs using a widget based development. Tk was originally released in 1991 with the original library written in C. Since then a number of Language Bindings have been released, including: Haskell, Ruby, Perl and Python.

Terminology

  • Window: The general rectangular area that is displayed on user’s screen, all other components are placed within the Window.
  • Frame: A rectangular area that can be used to divide up a Window for more complex layouts, considered the most basic Widget.
  • Widget : A generic term for any of the given building blocks that make up the GUI

1. Creating a Window

Being apart of the Python standard library you do not have to download or install it, rather you can just import it directly into your python files like any other library:

from tkinter import *
root_window = Tk()
root_window.mainloop()
A basic Tkinter window

Code so far:

from tkinter import *root_window = Tk()
root_window.mainloop()

Additional Window settings

Changing the title of your window: (Defaults to “ tk ”)

root_window.title("Your Title Here")
root_window.geometry("WIDTH x HEIGHT")
root_window.configure(background = "Color")

2. Adding basic Widgets

There are numerous different pre-built Widgets available within Tkinter, in this section we will go over the creation of the most commonly used ones.

labelName = Label(root_window, text = "Text to Display")
labelName.pack()
Label(root_window, text = "Text to Display").pack()

Label — for Static Text & Images

When displaying text:

Label(root_window, text = "Text to Display")
Label(root_window, image = "path/imageName.gif")

Button

The button can be used to call a Python function on click. The display text is what will be shown inside the button.

def function():
#some Python code
Button(root_window, text = "Text to Display", command = function)
def function(i):
#some Python code
Button(root_window, text = "Text", command =lambda: function(i))

Entry — User input through Text Field

The entry widget can be used to collect user input through a simple text input.

entryName = Entry(root_window)
userInputData = entryName.get()

Example of what we have learned so far

During our example we will be creating a basic login page. Let’s use what we learned about widgets and windows in order to begin. The code looks like the following:

from tkinter import *def loginHandler(username, password):
#Function that handles the login operations
root_window = Tk() #Creates window
root_window.title("Tutorial Login") #Gives title to window
root_window.geometry("500x500") #Makes the window size 500x500
#Create Label and Entry for username
Label(root_window, text = "Username:").pack()
userEntry = Entry(root_window)
userEntry.pack()
#Create Label and Entry for password
Label(root_window, text = "Password:").pack()
passwordEntry = Entry(root_window)
passwordEntry.pack()
#Get inputted data from the Entry widgets
submittedUsername = userEntry.get()
submittedPassword = passwordEntry.get()
#Create button that calls your loginHandler Function
funCall = lambda: loginHandler(submittedUsername, submittedPassword)
Button(root_window, text = "Login", command = funCall).pack()
root_window.mainloop()

3. Adding Frames

Frames are the most basic Widgets in Tkinter, however, I find them easier to think about as windows within our main (or Top-Level) window. Using frames you are able to further divide up your window into smaller squares, you can even stack frames within frames.

frameName = Frame(root_window)
frameName = Frame(root_window).pack()

Placing widgets inside a Frame

Now that we have our frame created, how do we use it? This is where Frames resemble the Window. As you may have noticed the first, and sometimes only, argument we use when creating a widget is what window we would like to create the widget in.

#Label created within the window
Label(root_window, text = "I'm in the Window").pack()
#Create a Frame inside the window and place the Label in the Frame
newFrame = Frame(root_window)
Label(newFrame, text = "I'm in the Frame").pack

Example of what we have learned so far

Continuing our Login Page example from before lets add in some frames. To help with the overall organization, and to make the positioning we will do next easier, lets divide our window into 2 Frames, one on top for out inputs and one on the bottom for our button.

from tkinter import *def loginHandler(username, password):
#Function that handles the login operations
root_window = Tk() #Creates window
root_window.title("Tutorial Login") #Gives title to window
root_window.geometry("500x500") #Makes the window size 500x500
#Create our Frames
topFrame = Frame(root_window).pack()
bottomFrame = Frame(root_window).pack(side = "bottom")
#Create Label and Entry for username
Label(topFrame, text = "Username:").pack()
userEntry = Entry(topFrame)
userEntry.pack()
#Create Label and Entry for password
Label(topFrame, text = "Password:").pack()
passwordEntry = Entry(topFrame)
passwordEntry.pack()
#Get inputted data from the Entry widgets
submittedUsername = userEntry.get()
submittedPassword = passwordEntry.get()
#Create button that calls your loginHandler Function
funCall = lambda: loginHandler(submittedUsername, submittedPassword)
Button(bottomFrame, text = "Login", command = funCall).pack()
root_window.mainloop()

4. Positioning our Widgets

To this point all our widgets have been stacked directly under the previous widget, centered in our Window / Frame. Although these GUIs are perfectly functional they do not look all that appealing, so let us cover how to move our widgets around.

Pack — Simple stacking

The pack positioning method is used to simply “pack” the given widget into the next available space within the window where the widget can fit. Most commonly this causes the widgets to be stacked vertically and centered within the window.

givenWidget = Label( ... )givenWidget.pack()
#The default value, packs widget along the top side of the parent
givenWidget.pack(side = "top")
#Packs widget along the bottom side of the parent
givenWidget.pack(side = "bottom")
#Other acceptable inputs are "left" and "right" respectively

Place — Exact positioning

The place positioning method is used to place widgets at exact positions within either the Window or Frame. There are two different ways to use place, either by pixels or by relative position.

givenWidget = Label( ... )givenWidget.place(x = "pixelAmount", y = "pixelAmount")
givenWidget.place(relx = "percentAmount", rely = "percentAmount")

Grid — Break down the window into a grid system

By far the most popular positioning method the grid method is used to break down the given Window / Frame into a series of rows and columns that can be used to place elements within that grid.

givenWidget = Label( ... )givenWidget.grid(row = "numberBefore", column = "numberBefore")

Example of what we have learned so far

Continuing our Login Page example from before lets wrap it up using our positioning we just learned. We will be adjusting the top frame so that each label is to the left of the given entry field.

from tkinter import *def loginHandler(username, password):
#Function that handles the login operations
root_window = Tk() #Creates window
root_window.title("Tutorial Login") #Gives title to window
root_window.geometry("250x100") #Makes the window size 500x500
#Create our Frames
topFrame = Frame(root_window).grid()
bottomFrame = Frame(root_window).grid(row = 1)
#Create Label and Entry for username
Label(topFrame, text = "Username:").grid(row = 0, column = 0)
userEntry = Entry(topFrame)
userEntry.grid(row = 0, column = 1)
#Create Label and Entry for password
Label(topFrame, text = "Password:").grid(row = 1, column = 0)
passwordEntry = Entry(topFrame)
passwordEntry.grid(row = 1, column = 1)
#Get inputted data from the Entry widgets
submittedUsername = userEntry.get()
submittedPassword = passwordEntry.get()
#Create button that calls your loginHandler Function
fun = lambda: loginHandler(submittedUsername, submittedPassword)
Button(bottomFrame, text = "Login", command = fun).grid(column=1)
root_window.mainloop()

Summary

At this point you should be comfortable creating basic GUIs with Tkinter, however this was not meant to be an exhaustive tutorial rather just an introduction. As you continue to build upon these skills you will find that we have simply scratched the service on what Tkinter has to offer. There are tons more methods and widgets built into the library to really bring your GUIs up to the next level. Using your basic understanding you have gained from this article I recommend checking out the official Tkinter Docs to continue to build upon your knowledge.

Additional example code

Using some additional styling options within Tkinter, that is not covered in detail in this introduction, we can further stylize our Login Page example.

from tkinter import *def loginHandler(username, password):
#Function that handles the login operations
root_window = Tk() #Creates window
root_window.title("Tutorial Login") #Gives title to window
root_window.geometry('300x100')
topFrame = Frame(root_window).grid()
bottomFrame = Frame(root_window).grid(row=1)
#Create Label and Entry for username
Ulab = Label(root_window, text = "Username:", font = "none 12 bold") Ulab.grid(row=0, column=0, sticky='e', padx = (10,0))
userEntry = Entry(root_window, font = "none 12")
userEntry.grid(row=0, column=1)
#Create Label and Entry for password
Plab = Label(root_window, text = "Password:", font = "none 12 bold")
Plab.grid(row=1, column=0, sticky='e')
passwordEntry = Entry(root_window, font = "none 12")
passwordEntry.grid(row=1, column=1)
#Get inputted data from the Entry widgets
submittedUsername = userEntry.get()
submittedPassword = passwordEntry.get()
#Create button that calls your loginHandler Function
fun = lambda: loginHandler(submittedUsername, submittedPassword)
sub=Button(root_window,text="Login",command=fun,font="none 10 bold")
sub.grid(column=1, sticky="e", pady = (10, 0))
root_window.mainloop()

The Startup

Get smarter at building your thing. Join The Startup’s +800K followers.

James Denbow

Written by

Motivated and versatile Computer Science graduate with a large amount of experience and passion for leadership.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

James Denbow

Written by

Motivated and versatile Computer Science graduate with a large amount of experience and passion for leadership.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store