Start With Python Tkinter

In this Python tutorial, I will introduce you to discuss Python GUI programming library used to create desktop applications. I will show what Python GUI is and what Python TKinter is, and how to use Tkinter in Python. I’ll walk you through the basics of setting up a GUI window, adding widgets like buttons and labels, etc.

Let’s start..

GUI Using Python

  • If you are a Python developer and want to create cool applications that support Graphical User Interface then you are in the right place. Here, we will learn how to create GUI-based applications using Python Tkinter. The word “Tkinter” is pronounced as “T-kin-ter “. We will read all about Python GUI programming.
  • In Python, Tkinter is used for creating Software whereas Turtle & Pygame are used for creating Graphic based animations & games.

Python Tkinter Installation

  • Python comes with a built-in Tkinter module so if you have Python installed you can execute the Tkinter program.
  • In case you want to know, how to install Python, then check Python download and Installation steps.
  • Type python -m tkinter on command-Prompt to quickly check for Tkinter. If the below kind of window appears, that means Tkinter is installed & you can skip this step.
Python GUI Programming (Tkinter) quick check
python gui programming
  • In case these windows don’t appear, then follow these steps: (Macintosh & Linux users can also follow these steps)

Step-1:

Check the version of Python installed in the system: python --version

Python GUI Programming (Tkinter) check python version

Step-2:

Go to python.org and download the same version of python. In my case, I have downloaded Python 3.7.9 for 64-bit.

Step-3:

Click on the installation file >> window will appear >> click on Modify.

Python GUI Programming (Tkinter) modify
python gui programming

Step-4:

Select the third option that reads Tcl/tk and IDLE , and then click Next, followed by install.

Python GUI Programming (Tkinter) install
Python tkinter installation

Step-5:

Type python -m tkinter on command-Prompt. If this window appeared that means tkinter is installed now.

Python GUI Programming (Tkinter) quick check
Python GUI Programming

Read Upload a File in Python Tkinter

Create First Program using Tkinter

Let me help you understand a bit more about Python GUI programming.

Before introducing any command, I want you to copy and paste the code into your code editor and try it once. This is a simple “Hello” program that will give an idea about what we are going to do.

python guides images\tkinter\Python GUI Programming (Tkinter) first program.png

Code:

# import modules
from tkinter import *

# configure workspace
ws = Tk()
ws.title("First Program")
ws.geometry('250x150')
ws.configure(bg="#567")

# function territory
def welcome():
    name = nameTf.get()
    return Label(ws, text=f'Welome {name}', pady=15, bg='#567').grid(row=2, columnspan=2)

# label & Entry boxes territory
nameLb = Label(ws, text="Enter Your Name", pady=15, padx=10, bg='#567')
nameTf = Entry(ws)

# button territory
welBtn = Button(ws, text="ClickMe!", command=welcome)

# Position Provide territory
nameLb.grid(row=0, column=0)
nameTf.grid(row=0, column=1)
welBtn.grid(row=1, columnspan=2)

# infinite loop 
ws.mainloop()
  • This program is just for reference. By the end of this blog, you will be able to write GUI-based software.
  • Before moving forward, let’s understand the flow of the program for tkinter-based applications.
Python GUI Programming (Tkinter) program flow
python tkinter example

The above-mentioned program is done in the same sequence & this sequence is followed in every Tkinter beginner program. This keeps the code clean and organized.

  1. Import the necessary modules or libraries.
  2. Workspace is created using: ws = Tk(), here “ws” can be replaced with any name. The most common ws replacements are root, window, win, master, etc. It is completely for your reference; in our case, it means workspace.
  3. An infinite loop is necessary to hold the screen. Without this loop, the screen will splash & disappear immediately.
  4. Label, entry boxes & buttons are the widgets. We will study them in detail later in the course.
  5. Button territory holds all the buttons.
  6. The widget has 3 parts as shown in the picture.
Python GUI Programming (Tkinter) widget formation
Python GUI programming.
  • Variable is the name assigned to the widget. All the activities performed on the widget will be stored under this name. This name can be used later to refer to this widget.
  • Widgets are Label, Entry, Button, message, Check button, Radio-button, etc. They have a dedicated task to perform. Apart from the task, they can be configured with additional utilities like color, font, etc.
  • Geometry refers to the position of a widget. Tkinter has 3 types of geometry (pack, grid, place). Each of them has a different way of placing a widget. Will know about them in detail in a later course.

Read Navigate Between Pages in a Python Tkinter

Python Tkinter widgets

  • GUI is all about widgets, as Python Tkinter widgets provide us controls using which user interacts with our application.
  • Label, Text boxes, List boxes, Buttons, Menu, etc are known as widgets. Each widget has its property.
  • There are 10 types of Python Tkinter widgets that I have explained individually one by one (with examples).
  • ws represents the parent window.

Python tkinter Label

  • A Python tkinter label is a simple piece of text or information.
  • The label is a very common & widely used widget.
  • The label is the first widget used before creating any application.

Syntax:

Label(ws, text=value )

Example:

This is the implementation of Label. Here, the text is assigned a value, “Enter Name”.

Code:

from tkinter import *

ws = Tk()

nameLb = Label(ws, text="Enter Name")
nameLb.pack()

ws.mainloop()

Output:

Enter Name was the value assigned in the label, so it is being displayed here.

Python Tkinter label widget
Python tkinter example

Check out Implement Drag and Drop Functionality in Python Tkinter

Python tkinter Entry

Let us discuss Python tkinter Entry.

  • Entry boxes are used to take user input.
  • This is another widely used widget.

Syntax:

Entry(ws)

Example:

This is the implementation of Entry boxes. It will display an empty box ready to be filled by the user.

Code:

from tkinter import *

ws = Tk()

nameTf = Entry(ws)
nameTf.pack()

ws.mainloop()

Output:

The output displays an empty text box where “Type Text Here!” is written by the user.

Python Tkinter widget Entry box
Python tkinter Entry

Read Create a Date Time Picker using Python Tkinter

Python tkinter Button

Let me discuss Python tkinter Button.

  • The button triggers an action.
  • The button takes command as an argument that does all the magic.

Syntax:

Button(ws, command=<action>)

Example:

This is the implementation of Button. display text provided is “submit” and the command passed is function: Submit. On clicking the button function will be triggered.

Code:

from tkinter import *

ws = Tk()

def submit():
    return Label(ws, text="Submitted!").pack()

submitBtn = Button(ws, text="submit", command=submit)
submitBtn.pack()

ws.mainloop()

Output:

The function was to create another label with the text “Submitted“. So the output shows the small text below the button. It is created after the button is clicked.

Python GUI Programming (Tkinter) message box
Python Tkinter Button

Read Display Data in Textboxes using Python Tkinter

Python tkinter message box

  • The Python message box is a pop-up box with a message.
  • To use the message box, import the message box module.
  • There are six types of message prompts, such as:
  • askquestion: Prompts “Yes”, “No” options. Returns Yes or No.
  • askyesno: Prompts with “Yes”, “No” options. Yes returns 1 and No returns 0.
  • askretrycancel: Prompts with the option to “retry” or “cancel. With sound, Retry returns 1, and cancel returns 0.
  • showerror: Displays an error message with sound. returns “Ok”.
  • showinfo: Displays a message with sound. returns “Ok”.
  • show warning: Displays warning message with sound. returns “Ok”.

Syntax:

messagebox.function(title, message)

Example:

Here is an example of all the message boxes using Python tkinter. All types of messages are put under one function that will be triggered with one button.

Code:

from tkinter import *
from tkinter import messagebox

ws = Tk()

def prompts():
    messagebox.showinfo("showinfo", "Hi there!")
    messagebox.showwarning("showinfo", "Hi there!")
    messagebox.showerror("showinfo", "Hi there!")
    messagebox.askquestion("showinfo", "Hi there!")
    messagebox.askyesno("showinfo", "Hi there!")
    messagebox.askretrycancel("showinfo", "Hi there!")
    
Button(ws, text="Click Me!", command=prompts).pack()

ws.mainloop()

Output:

The moment Click Me! button is pressed, these prompts start appearing in the sequence.

Python GUI Programming (Tkinter) message box
Python tkinter message box

Check out Set a Background Image in Python Tkinter

Python tkinter checkbox

  • Python Checkboxes are a selection widget.
  • Multiple items can be selected.
  • The return type could be a string or an integer.
  • For integers, we can use IntVar().
  • For strings, We can use StringVar().

Syntax:

var = IntVar()
Checkbutton(ws, text= , variable=var).pack()

Example:

This is the implementation of the check button. Here are multiple options for preparing tea. User can check and mark them as per their preference.

from tkinter import *

ws = Tk()
Label(ws, text="Tea", font=(24)).pack()
var1 = IntVar()
Checkbutton(ws, text="Milk", variable=var1).pack()
var2 = IntVar()
Checkbutton(ws, text="Sugar", variable=var2).pack()
var3 = IntVar()
Checkbutton(ws, text="Ginger", variable=var3).pack()
var4 = IntVar()
Checkbutton(ws, text="Lemon", variable=var4).pack()

ws.mainloop()

Output:

In this output, the user chooses to prepare tea using milk, sugar & ginger only. Since Lemon is not selected, so it will not be considered.

Python Gui programming (tkinter) check boxes
Python tkinter checkbox

Read Create Window Titles in Python Tkinter

Python tkinter radiobutton

  • Python tkinter Radiobutton is another selecting widget like a checkbox
  • It allows a single selection of items only.
  • The return type could be a string or an integer.
  • For integer value, We can use IntVar().
  • For string value, We can use StringVar().
  • The same variable is assigned to all the radio buttons to keep them under one group.

Syntax:

var = IntVar()
Radiobutton(ws, text= ,variable=var, value= ).pack()

If the value is in string, then replace IntVar() with StringVar().

Example:

Radiobutton is used only for a single selection. So here we have assumed that a candidate has an offer letter from all the mentioned companies, but the catch is that he can only join one company. So he is provided with the options.

Code:

from tkinter import *

ws = Tk()

var = IntVar()
Label(ws, text="Choose one", font=(18)).pack()
Radiobutton(ws, text="Google", variable=var, value=1).pack()
Radiobutton(ws, text="Facebook", variable=var, value=2).pack()
Radiobutton(ws, text="Amazon", variable=var, value=3).pack()
Radiobutton(ws, text="Microsoft", variable=var, value=4).pack()

ws.mainloop()

Output:

So the candidate chose to go with Google. Google radiobutton is selected.

Python GUI Programming (Tkinter) radiobutton
Python tkinter radiobutton

Read Create an OptionMenu in Python Tkinter

Python tkinter listbox

  • The Python tkinter listbox is also a selection widget.
  • Items are displayed in a widget box.
  • It provides a scrolling feature.

Syntax:

var_name = Listbox(ws)
var_name.pack()

var_name.insert(index, value)

Example:

In this army, alphabets are listed using a Listbox.

Code:

from tkinter import *

ws = Tk()
ws.geometry("300x300")

alphabets = Listbox(ws)
alphabets.pack()

alphabets.insert(0, "Alpha")
alphabets.insert(1, "Bravo")
alphabets.insert(2, "Charlie")
alphabets.insert(3, "Delta")

ws.mainloop()

Output:

A list of army alphabets is displayed. Users can select single or multiple options

Python GUI Programming (Tkinter) listbox
Python tkinter listbox

Check out Create Responsive Layouts with Python Tkinter’s Grid Geometry Manager

Python tkinter optionmenu

Let us check an example on Python tkinter optionmenu.

  • OptionMenu button is similar to the List box.
  • It displays items in a drop-down format.
  • It can be placed in less space.

Syntax:

var-name = StringVar()
alphabets = Optionmenu(ws, var-name, "item-1", "item-2", "item-n")
alphabets.pack()

Example:

This is the implementation of optionmenu wherein army alphabets are used to display in a dropdown form.

code:

from tkinter import *

ws = Tk()
ws.geometry("200x100")

items = StringVar()
items.set("Alpha")

alphabets = OptionMenu(ws,items, "Alpha", "Bravo", "Charlie", "Delta")
alphabets.pack()

ws.mainloop()

Output:

In this implementation of Optionmenu. Alpha is set to default. When a user clicks on this box, the options are displayed as like below.

Python GUI Programming (Tkinter) Option menu
Python Tkinter optionmenu

Read Create Layouts with Python Tkinter Frame

Python tkinter labelframe

Let us see how to use Python tkinter labelframe.

  • It adds a frame to the current window.
  • It is used to create sections or groups.
  • It improves the GUI.

Syntax:

var-name = LabelFrame(ws, text=value)
var-name.pack()

Example:

This is the implementation of LabelFrame. Here Gender & Food are sections.

Code:

from tkinter import *

ws = Tk()

genF = LabelFrame(ws, text="Gender")
genF.pack()

var = IntVar()
Radiobutton(genF, text="Male", variable=var, value=1).pack()
Radiobutton(genF, text="Female", variable=var, value=2).pack()

food = LabelFrame(ws, text="Food")
food.pack()
Checkbutton(food, text="snacks").pack()
Checkbutton(food, text="Drinks").pack()
Checkbutton(food, text="Meal").pack()

ws.mainloop()

Output:

LabelFrame has made this output self-explanatory. Now we know that there are two sections: Gender & Food. & each section has items.

image 36
Python tkinter labelframe

Read Create a Progress Bar in Python Tkinter

Python tkinter Menu

  • Python tkinter Menu is the options present on the top-left corner of the window
  • These options provide a wide variety of controls.
  • File, Edit, Help, etc are some of the basic options in every window.

Syntax:

var-name = Menu(ws, command=<action>)
ws.config(menu=var-name)

Example:

This is the implementation of the Python Menu bar. Three popular menus (File, Edit, Help) are created, and when the user clicks on them, a message is printed on the terminal or command line.

Code:

from tkinter import *

ws = Tk()  
  
def fileSec():  
    print("File section")  

def editSec():  
    print("Edit section")  

def helpSec():  
    print("Help section")  
  
mb = Menu(ws)  
mb.add_command(label="File", command=fileSec)  
mb.add_command(label="Edit", command=editSec) 
mb.add_command(label="Help", command=helpSec)   
  
ws.config(menu=mb)  
  
ws.mainloop()  

Output:

This is the implementation of the Menu bar. In the top left corner, you will see the menu. File, Edit, and Help.

Python GUI Programming (Tkinter) menu bar
Python tkinter Menu

Check out Master the Python Tkinter Canvas

Geometry Management

There are three types of Python Geometry Management such as:

1. Pack

  • The pack is a geometry manager.
  • It fills the space & sticks to the center,
  • It is good for small applications.
  • One can quickly start with the pack as it does not require arguments.

Syntax:

widget.pack()

Example:

This is the implementation of the pack. Here 4 labels are used to display messages.

Code:

from tkinter import *

ws = Tk()

Label(ws, text="Placing").pack()
Label(ws, text="Text ").pack()
Label(ws, text="using ").pack()
Label(ws, text="Pack is fun").pack()

ws.mainloop()

Output:

Pack adjusts itself in the center of the screen so in the next image you can see that even after resizing the image, pack text remains in the center.

Geometry Management
Python Geometry Management
Python GUI programming with Tkinter

2. Grid

  • Grid maintains the widgets in a tabular form.
  • It sticks to the left top if the window is resized.
  • The grid needs 2 necessary arguments: rows & columns.
  • Here is the row & column explanation.
Python GUI Programming (Tkinter) row column explanation
python gui programming with tkinter

Syntax:

widget.grid(row= value ,column= value )

So here, value equals to the number you want to provide with respect to row & column.

Example:

This is the implementation of the grid. Python Grid works in a row & column format.

Code:

from tkinter import *

ws = Tk()

Button(ws, text="These buttons").grid(row=0, column=0)
Button(ws, text="are positioned").grid(row=0, column=1)
Button(ws, text="using Grid").grid(row=0, column=2)

Button(ws, text="This is ").grid(row=1, column=0)
Button(ws, text="another line").grid(row=1, column=1)
Button(ws, text="using Grid").grid(row=1, column=2)

ws.mainloop()

Output:

Six buttons are displayed using a grid. each button has its row & value.

Geometry Management in python

3. Place

  • The place is used to provide a fixed position for the widget.
  • It provides maximum control to the user.
  • Widgets remain in the assigned position
  • x & y values are provided with an anchor.
  • anchor comes with 8 variations
    • NE: North-East
    • N: North
    • NW: North-West
    • E: East
    • W: West
    • SE: South-East
    • SW: South-West
    • S: South

Syntax:

widget.place(x = value,  y = value, anchor=location )

Example:

This is the implementation of the place. The place needs x and y coordinates.

Code:

from tkinter import *

ws = Tk()
ws.geometry("300x300")

Button(ws, text="North-West").place(x=50, y=20, anchor="center")
Button(ws, text="North").place(x=148, y=20, anchor="center")
Button(ws, text="North-South").place(x=250, y=20, anchor="center")
Button(ws, text="East").place(x=50, y=148, anchor="center")
Button(ws, text="West").place(x=250, y=148, anchor="center")
Button(ws, text="South-East").place(x=50, y=250, anchor="center")
Button(ws, text="South").place(x=148, y=250, anchor="center")
Button(ws, text="South-West").place(x=250, y=250, anchor="center")
Button(ws, text="Center").place(x=148, y=148, anchor="center")

ws.mainloop()

Output:

Here nine buttons are implemented on the screen. Each one is placed in the direction i.e North, South, east, west, etc.

Geometry Management in python
Python GUI programming with Tkinter

Differences between Pack, Grid, and Place

The table below represents the difference between Python Pack, Grid, and Place.

PackGridPlace
Pack positions the widget in a sequence.
One after another.
Grid places widgets in a row & column-wiseThe grid requires a Row & column from the user as an argument
The pack does not require mandatory argumentEverything remains in its position. If the window size is reduced, then widgets will start disappearing.Place needs x & y coordinates as an argument
widgets stick to the center when the window is resized.Widgets stick to the top-left corner when the window is resizedno manual control of widget positioning
It allows to be positioning the exact place where the user wants it.It provides more control over widget positioningIt allows to be positioning the exact place where the user wants it.
It works in a tabular form. So the value provided in row & column can position the widget.It works in a tabular form. So the value provided in row & column can position the widget.Place is best at positioning widgets in the exact position as defined in x & y coordinates

Read Set and Manage Window Size in Python Tkinter

Mini Project using Python Tkinter

Let us develop a small Python project.

This is a simple Login & Register mechanism using Python Tkinter. You use the code for further development. The program is based on the topics you learned above.

Step 1. This is the first page that will appear. It will require a username & password before you proceed. the default username is “python” & the password is “guides“.

Python GUI Programming (Tkinter) login page
Python Tkinter control

Step 2. In case you have entered the wrong credentials, i.e., username or password, then an error message box will appear. In case you don’t have an email and password, you can create one using the Register button.

Python GUI Programming (Tkinter) login error page
python tkinter tutorial

Step 3. Fill in the form and press Register. It prompts with the info message saying sign-up successfully, which means you are registered now.

python gui programming (tkinter) signup successful example
Python Tkinter Example

Step 4. If the credentials, i.e, username & password, are correct, then an info message box will display a message “Login Successfully”.

python gui programming (tkinter) login successful example
Python tkinter examples

Code:

# import module
from tkinter import *
from tkinter import messagebox

# configure 
ws = Tk()
ws.title("Login Page")
ws.geometry("300x250")

# functions
def checkCred():
    email = email_tf.get()
    pwd = pwd_tf.get()
    print(email, pwd)
    if email == "python" and pwd == "guides":
        return messagebox.showinfo("Login", "Login Sucessfully!")
    else:
        return messagebox.showerror("Login", "Login Failed!")
def success_msg():
    return messagebox.showinfo("Signup", "Sign-up Successfully")
    
def register():
    ws = Tk()
    ws.title("Register")
    ws.geometry("300x250")

    Label(ws, text="Enter Name").place(x=50, y=20, anchor="center")
    nTf =Entry(ws).place(x=170, y=20, anchor=CENTER)
    Label(ws, text="Enter Email").place(x=50, y=60, anchor=CENTER)
    eTf = Entry(ws).place(x=170, y=60, anchor=CENTER)
    Label(ws, text="Password").place(x=50, y=100, anchor=CENTER)
    pTf = Entry(ws).place(x=170, y=100, anchor=CENTER)
    Label(ws, text="re-enter Password").place(x=50, y=140, anchor=CENTER)
    rpTf = Entry(ws).place(x=170, y=140, anchor=CENTER)
    Button(ws, text="Register", command=success_msg).place(x=100, y=180, anchor=CENTER)
    
# write code
email_lb = Label(ws,text="Enter Email")
email_tf = Entry(ws)
pwd_lb = Label(ws,text="Enter Password")
pwd_tf = Entry(ws)
login_btn = Button(ws, text="Login", command=checkCred)
reg_btn = Button(ws, text="Register", command=register)

# placeholder
email_lb.place(x=50, y=40, anchor=CENTER)
email_tf.place(x=170, y=40, anchor=CENTER)
pwd_lb.place(x=50, y=80, anchor=CENTER)
pwd_tf.place(x=170, y=80, anchor=CENTER)
login_btn.place(x=100, y=120, anchor=CENTER)
reg_btn.place(x=180, y=120, anchor=CENTER)

# infinite loop
ws.mainloop()

10 best project Ideas using Python Tkinter

Here is the list of Python projects using Tkinter.

  1. Rock Paper Scissors game using Python Tkinter
  2. Email interface with basic widgets using Python Tkinter
  3. Digital clock with sun image that changes every hour.
  4. Password manager, using the Python Tkinter & SQLite database
  5. Password generator using Python Tkinter.
  6. The lottery system uses Python Tkinter.
  7. Toss system with the option to choose any number of winners.
  8. Tic Tac Toe Game using Python Tkinter
  9. Billing Management system using Python Tkinter
  10. Stopwatch with database later performs data analysis using machine learning.

You may like the following Python tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.