How to Create a Simple Image Viewer with Python? |
In this article, we will go through the steps of creating a simple image viewer app using Python's GUI library Tkinter. This app allows the user to navigate through a folder of images, viewing each one in turn.
Introduction
Have you ever wanted to view a folder of images in an organized manner? Well, look no further! With a little bit of Python code, you can create a simple image viewer that does exactly that. We'll be using Tkinter, a popular Python GUI library, to make this app.
Building the App
The first step in building the image viewer app is to import the required libraries and create a GUI window using Tkinter. You'll then need to specify the dimensions of the window, as well as its title, font, and other visual elements.
Once the window is set up, you can start adding widgets to it. In this case, we'll be using label widgets to display the images. To navigate through the images, we'll add buttons for "Next" and "Previous" navigation. The code will load the next or previous image in the folder based on the button that is pressed.
Adding Functionality
Finishing Up
Food for Thought
Example
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image, ImageTk
import os
class ImageViewer:
def __init__(self, master):
self.master = master
self.master.title("Python Simple Image Viewer")
self.master.geometry("600x600")
self.top_frame = tk.Frame(self.master, width=600, bd=1, relief="solid")
self.top_frame.pack(side="top", fill="both", expand="yes")
self.mid_frame = tk.Frame(self.master, width=300, height=200, bd=1, relief="solid")
self.mid_frame.pack(side="top")
self.images = []
self.location = 0
self.lbl_title = tk.Label(self.top_frame, text="Label", font=("Arial", 20))
self.lbl_title.pack()
self.forward = tk.Button(self.top_frame, text="Forward", command=lambda: self.load_image(1))
self.forward.pack(side="left")
self.back = tk.Button(self.top_frame, text="Back", command=lambda: self.load_image(-1))
self.back.pack(side="left")
self.parse_folder()
def parse_folder(self):
file_path = filedialog.askdirectory()
if not file_path:
messagebox.showerror("Error", "No folder selected.")
return
try:
for file in os.listdir(file_path):
if file.endswith(".jpg") or file.endswith(".png"):
self.images.append(os.path.join(file_path, file))
except Exception as e:
messagebox.showerror("Error", str(e))
return
if not self.images:
messagebox.showerror("Error", "No images found in the selected folder.")
return
self.load_image(0)
def load_image(self, direction):
self.location += direction
if self.location >= len(self.images):
self.location = 0
elif self.location < 0:
self.location = len(self.images) - 1
image = Image.open(self.images[self.location])
image = image.resize((300, 200), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)
self.lbl_title.config(image=image)
self.lbl_title.image = image
if __name__ == "__main__":
root = tk.Tk()
viewer = ImageViewer(root)
root.mainloop()