Python GUI Programming (Python Tkinter)

By: On:

Want to know more about Python GUI programming? In this Python tutorial, we will discuss about python gui programming, basically we will see what is Python GUI and what is Python TKinter. How to use Tkinter in Python. Also, We will see these below thing as:

  • How to Download & Install Tkinter in Python
  • Create First Program using Tkinter
  • What are the Python Tkinter widgets
  • What are the Geometry Management (Pack, Grid, Place)
  • Differences between Pack, Grid, and Place
  • Mini Project using Python Tkinter
  • 10 best project Ideas using python Tkinter

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 this below kind of window appeared that means tkinter is installed & you can skip this step.
Python GUI Programming (Tkinter) quick check
python gui programming
  • In case these window doesn’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 of 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

Create First Program using Tkinter

Let us try to understand a bit more on Python gui programming.

Before introducing to any command we want you to copy and paste the code in 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 application.
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 own 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 & button 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.

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 own 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 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 label so it is being displayed here.

Python Tkinter label widget
python tkinter example

Python tkinter Entry

Let us discuss about 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:

Output displays an empty text box where in “Type Text Here!” is written by user.

Python Tkinter widget Entry box
Python tkinter Entry

Python tkinter Button

Let us discuss about Python tkinter Button.

  • Button triggers action.
  • 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 button. It is created after button is clicked.

Python Tkinter widget Button
Python tkinter Button

Python tkinter message box

  • The Python message box is a pop-up box with a message.
  • To use message box, import message box module.
  • There are Six types of messages prompts such as:
    • showinfo : Displays message with sound. returns “Ok”
    • showwarning : Displays warning message with sound. returns “Ok”
    • showerror : Displays error message with sound. returns “Ok”
    • 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 return 0

Syntax:

messagebox.function(title, message)

Example:

Here is the 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

Python tkinter checkbox

  • Python Checkboxes are a selection widget.
  • Multiple items can be selected.
  • Return type could be string or integer.
  • For integer, 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 check button. Here multiple options for preparing tea is provided. User can check 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 user choose 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

Python tkinter radiobutton

  • Python tkinter Radiobutton is another selecting widget like a checkbox
  • It allows a single selection of items only.
  • Return type could be string or 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 single selection. So here we have assumed that a candidate has offer letter of all the mentioned companies but the catch is 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 choose to go with Google. Google radiobutton is selected.

Python GUI Programming (Tkinter) radiobutton
Python tkinter radiobutton

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

List of army alphabets are displayed. User can select single or multiple options

Python GUI Programming (Tkinter) listbox
Python tkinter listbox

Python tkinter optionmenu

Let us check an example on Python tkinter optionmenu.

  • OptionMenu button is similar to the List box.
  • It displays item 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 user clicks on this box, then options are displayed as like below.

Python GUI Programming (Tkinter) Option menu
python tkinter optionmenu

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 now that there are two sections Gender & Food. & each section has items.

image 36
Python tkinter labelframe

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

Geometry Management

There are three types of Python Geometry Management such as:

  1. Pack
  2. Grid
  3. Place

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 in-respect to row & column.

Example:

This is the implementation of 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 grid. each button has its row & value.

Geometry Management in python

3. Place

  • Place is used to provide fix position to widget.
  • It provides maximum control to user.
  • widgets remain in the assigned position
  • x & y values are provided with 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 place. 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

Below table 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 wisePlace poitions widget exactly where user want.
Pack do not require mandatory argumentThe grid requires Row & column from the user as an argumentPlace 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 resizedEverything remains in it’s position. If window size is reduced than widgets will start disappear.
no manual control on widget positioning It provides more control over widget positioningIt allows to position the widget exact place where user want.
place is for quick uses as it is easy to implement. It do not allow to control the position of widget.It works in a tabular form. So value provided in row & column can position widget.Place is best at positioning widgets in the exact position as defined in x & y coordinates

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 upon 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 wrong credentials i.e username or password then error message box will appear. In case you don’t have email and password you can create one using 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 that means you are register now.

python gui programming (tkinter) signup successful example
python tkinter example

Step 4. If the credential i.e username & password is 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)


# placeholders
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 Scissor 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 using 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:

In this Python Tutorial, we learned about Python Gui programming.

  • GUI using python
  • Download & Install Tkinter
  • Create First Program using Tkinter
  • Python Tkinter widgets
  • Geometry Management (Pack, Grid, Place)
  • Differences between Pack, Grid, and Place
  • Mini Project using Python Tkinter
  • 10 best project Ideas using python Tkinter

Leave a Comment