Create an Image Viewer Application using Python Tkinter

It's an image viewer application in python using the tkinter library

Introduction

Every operating system(mobile and desktop both) offers a by-default image viewer application to display a selected image or multiple images as per the user's choices. 

In this tutorial, we'll create our own Image Viewer using Python Language.

Users can display one or multiple images through it. We'll try to make it almost the similar to the application that comes with the operating system, by-default.

👉Visit Also: Create an Image Rotator Application using Python

How our Image Viewer Application Works?

Our Image Viewer application offers users select one and multiple images for displaying. They can select a directory too where the images are already there. 

There are two buttons to see the previous or next image(if multiple images are there).

If the users open a directory, the program will try to find '.jpg', '.jpeg', and '.png' files in there. If any matches are found, the program will store the location of those image files into a python list and starts displaying with the first one.

★Most important feature of this Image Viewer Application is when the displaying image reaches the end, it starts with the first image again(for the next) and when the displaying image reaches the first one, it starts with the last image again(for the previous).

What can you learn from this project?

  • Creating a graphical interface with Tkinter: Creating Tkinter window, frame, label, buttons, etc.
  • Displaying an image on Tkinter Window using another function(out of the main function)
  • Object-Oriented Programming: Use of Classes, objects, etc.

Requirements

You just need to install these libraries to view your images through this application.

☛Install Tkinter: pip install tk

☛Install Pillow: pip install Pillow

Import the Modules

Let's create a Python file with the name "ImageViewer.py" and start writing the code by importing these modules.


import glob
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog, messagebox

Declare the Image Viewer Class

The Image_Viewer Class


class Image_Viewer:

Create a window

Declare the __init__() function and create a Tkinter Window, and set the size, title, background color, resizable option, etc. here.


def __init__(self, root):
self.window = root
self.window.geometry("960x600")
self.window.title('Image Viewer')
self.window.configure(bg='gray20')
self.window.resizable(width = False, height = False)

Declare some variables

Declare these variables that are gonna used in the upcoming code. Initially, self.img and self.Image_Path contains the None value; later it will carry the image data and the image path respectively.

We're following this way to avoid vanishing the image from the window when another function is called for displaying the image(Please visit this article to know more: Display an Image on Tkinter Window in Another Function).

self.Image_List stores the image's path and self.cur_index maintain the index of the current displaying image(on the tkinter window) from that list.


# Declare some variables that
# initially store None value
self.img = img
self.Image_Path = image_path

self.Image_List = list()
self.cur_index = 0

Declare the frame size

Declaring the frame size here, where we'll show our images.


self.width = 740
self.height = 480

Create the menu bar


# Creating Menubar
self.menubar = Menu(self.window)
# Adding Edit Menu and its sub menus
edit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Open', menu=edit)
edit.add_command(label='Open Image',command=self.Open_Image)
edit.add_command(label='Open Images',command=self.Open_Images)
edit.add_command(label='Open Folder',command=self.Open_Folder)

# Adding About Menu
about = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='About', menu=about)
about.add_command(label='About', command=self.About_Window)

# Exit the Application
exit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Exit', menu=exit)
exit.add_command(label='Exit', command=self.Exit)

# Configuring the menubar
self.window.config(menu=self.menubar)

Create the buttons


# Buttons
prev_btn = Button(self.window, text="Prev", \
font=("Helvetica", 15, 'bold'), command=self.Prev_Image)
prev_btn.place(x=15,y=270)

next_btn = Button(self.window, text="Next", \
font=("Helvetica", 15, 'bold'), command=self.Next_Image)
next_btn.place(x=865,y=270)

Create a frame to show the image


# Creating a Frame
self.frame_1 = Frame(self.window, \
bg='gray20',width=self.width,height=self.height)
self.frame_1.pack()
self.frame_1.place(anchor='center', relx=0.5, rely=0.5)

Declare the Miscellaneous Functions

Let's do a smart task. Here, we'll declare some functions that are gonna used by the rest of the functions for different purposes. 

I've declared one single comment line for each function. It will help you to understand the objectives better.


# Remove all widgets from the frame_1
def Clear_Screen(self):
for widget in self.frame_1.winfo_children():
widget.destroy()

# About window
def About_Window(self):
messagebox.showinfo("Image Viewer", \
"Image Viewer 22.05;\nDeveloped by Subhankar Rakshit")

# It destroys the main GUI window of the
# application
def Exit(self):
self.window.destroy()

Declare a function to open only one image

It will let users select only one image through the Tkinter file dialog.


# Open an Image
def Open_Image(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.Image_Path = \
filedialog.askopenfilename(initialdir = "/", \
title = "Select an Image", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
self.Image_List.append(self.Image_Path)
# Show the fisrt image
self.Show_Image(0)

Declare a function to open multiple images

It will let users select multiple images through the Tkinter file dialog.

selecting multiple image files for viewing through the python image viewer - PySeek
Selecting Multiple Images through the File Dialog

# Open Multiple Images
def Open_Images(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.Image_Path = \
filedialog.askopenfilenames(initialdir = "/", \
title = "Select Images", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
for path in self.Image_Path:
self.Image_List.append(path)
# Show the fisrt image
self.Show_Image(0)

Declare a function to open a directory

It will let users select only a directory through the Tkinter file dialog.


# Open a directory
def Open_Folder(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.directory = filedialog.askdirectory()
if self.directory != '':
for filename in glob.iglob(self.directory + '**/*.jpg', recursive=True):
self.Image_List.append(filename)
# Show the fisrt image
self.Show_Image(0)

Show the Image

Let's create a function to display the image on the 'frame_1' of the main window.


# Show the selected Image
def Show_Image(self, index):
image = Image.open(self.Image_List[index])
resized_image = image.resize((self.width, self.height))

# Create an object of tkinter ImageTk
self.img = ImageTk.PhotoImage(resized_image)

# Create a Label Widget to display the text or Image
label = Label(self.frame_1, image=self.img)
label.pack()

Previous Image

Whenever the 'Prev' button is pressed, this function gets a call and displays the previous image of the present.

When the displaying image will reach the first one, it will start with the last image again.


# It displays the previous image
def Prev_Image(self):
if self.cur_index > 0 and self.cur_index < len(self.Image_List):
self.cur_index -= 1
self.Clear_Screen()
self.Show_Image(self.cur_index)
# The image will display from the end
else:
self.cur_index = len(self.Image_List) - 1
self.Clear_Screen()
self.Show_Image(self.cur_index)

Next Image

Whenever the 'Next' button is pressed, this function displays the next image of the present one. 

When the displaying image will reach the end, it will start with the first one again.


# It displays the next image
def Next_Image(self):
if self.cur_index < len(self.Image_List) - 1:
self.cur_index += 1
self.Clear_Screen()
self.Show_Image(self.cur_index)
# The image will display from the start again
else:
self.cur_index = 0
self.Clear_Screen()
self.Show_Image(self.cur_index)

The Main Function

Now it's time to lead the whole program. Let's declare the main function for this.


# The main function
if __name__ == "__main__":
root = Tk()
# Creating these objects for avoiding
# image vanishing(Garbage Collector)
img = None
image_path = None
# Creating a Image_Rotator class object
obj = Image_Viewer(root)
root.mainloop()

Full Code

Here is the full code for your convenience.


'''Image Viewer using Python
Copyright (c) 2022 Subhankar Rakshit
~PySeek~'''

import glob
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog, messagebox

class Image_Viewer:
def __init__(self, root):
self.window = root
self.window.geometry("960x600")
self.window.title('Image Viewer')
self.window.configure(bg='gray20')
self.window.resizable(width = False, height = False)

# Declare some variables that
# initially store None value
self.img = img
self.Image_Path = image_path

self.Image_List = list()
self.cur_index = 0

self.width = 740
self.height = 480

# ==============================================
# ================Menubar Section===============
# ==============================================
# Creating Menubar
self.menubar = Menu(self.window)
# Adding Edit Menu and its sub menus
edit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Open', menu=edit)
edit.add_command(label='Open Image',command=self.Open_Image)
edit.add_command(label='Open Images',command=self.Open_Images)
edit.add_command(label='Open Folder',command=self.Open_Folder)

# Adding About Menu
about = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='About', menu=about)
about.add_command(label='About', command=self.About_Window)

# Exit the Application
exit = Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label='Exit', menu=exit)
exit.add_command(label='Exit', command=self.Exit)

# Configuring the menubar
self.window.config(menu=self.menubar)
# ===================End=======================

# Buttons
prev_btn = Button(self.window, text="Prev", \
font=("Helvetica", 15, 'bold'), command=self.Prev_Image)
prev_btn.place(x=15,y=270)

next_btn = Button(self.window, text="Next", \
font=("Helvetica", 15, 'bold'), command=self.Next_Image)
next_btn.place(x=865,y=270)

# Creating a Frame
self.frame_1 = Frame(self.window, \
bg='gray20',width=self.width,height=self.height)
self.frame_1.pack()
self.frame_1.place(anchor='center', relx=0.5, rely=0.5)

# Remove all widgets from the frame_1
def Clear_Screen(self):
for widget in self.frame_1.winfo_children():
widget.destroy()

# About window
def About_Window(self):
messagebox.showinfo("Image Viewer", \
"Image Viewer 22.05;\nDeveloped by Subhankar Rakshit")

# It destroys the main GUI window of the
# application
def Exit(self):
self.window.destroy()

# Open an Image
def Open_Image(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.Image_Path = \
filedialog.askopenfilename(initialdir = "/", \
title = "Select an Image", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
self.Image_List.append(self.Image_Path)
# Show the fisrt image
self.Show_Image(0)

# Open Multiple Images
def Open_Images(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.Image_Path = \
filedialog.askopenfilenames(initialdir = "/", \
title = "Select Images", \
filetypes = (("Image files", "*.jpg *.jpeg *.png"),))
if len(self.Image_Path) != 0:
for path in self.Image_Path:
self.Image_List.append(path)
# Show the fisrt image
self.Show_Image(0)

# Open a directory
def Open_Folder(self):
self.Clear_Screen()
self.Image_List.clear()
self.cur_index = 0

self.directory = filedialog.askdirectory()
if self.directory != '':
for filename in glob.iglob(self.directory + '**/*.jpg', recursive=True):
self.Image_List.append(filename)
# Show the fisrt image
self.Show_Image(0)

# Show the selected Image
def Show_Image(self, index):
image = Image.open(self.Image_List[index])
resized_image = image.resize((self.width, self.height))

# Create an object of tkinter ImageTk
self.img = ImageTk.PhotoImage(resized_image)

# Create a Label Widget to display the text or Image
label = Label(self.frame_1, image=self.img)
label.pack()

# It displays the previous image
def Prev_Image(self):
if self.cur_index > 0 and self.cur_index < len(self.Image_List):
self.cur_index -= 1
self.Clear_Screen()
self.Show_Image(self.cur_index)
# The image will display from the end
else:
self.cur_index = len(self.Image_List) - 1
self.Clear_Screen()
self.Show_Image(self.cur_index)

# It displays the next image
def Next_Image(self):
if self.cur_index < len(self.Image_List) - 1:
self.cur_index += 1
self.Clear_Screen()
self.Show_Image(self.cur_index)
# The image will display from the start again
else:
self.cur_index = 0
self.Clear_Screen()
self.Show_Image(self.cur_index)

# The main function
if __name__ == "__main__":
root = Tk()
# Creating these objects for avoiding
# image vanishing(Garbage Collector)
img = None
image_path = None
# Creating a Image_Rotator class object
obj = Image_Viewer(root)
root.mainloop()

👉Visit AlsoBuild a PDF Editor using Python: Split, Merge, and Rotate

Summary

In this tutorial, we've build an Image Viewer using Application using Python. We have made it most advanced ever.

Not only single, you can display multiple images through it one after one. It almost looks like the similar to the original application that comes with the operating system.

For any issue related to this project, please drop your comment below. You'll get an immediate response.

To get more lovely Tkinter Examples, visit the separate page created only for Python Projects. Some examples are given below.

👉Language Translator App with Python Tkinter - Google Translate

👉Image to Pencil Sketch Converter in Python - Tkinter Project

👉Image to Cartoon Converter in Python - Tkinter Project

👉An Advanced Alarm Clock using Python Tkinter

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post