Python implements GUI image browsing program

Python implements GUI image browsing program

The following program requires the pillow library. Pillow is a third-party image processing library for Python that needs to be installed to be practical. Pillow is developed on the basis of PIL (Python Imaging Library). It should be noted that the pillow library is installed with pip install pillow, and PIL is used when importing the package. to import. More information can be foundhttps://blog.csdn.net/cnds123/article/details/126141838

1. Simple picture viewing program

Function, uses the tkinter library to create a window through which the user can select a picture and display it in the window. Ability to resize window to fit image. The renderings are as follows:

The source code is as follows:

import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk

# 创建一个Tkinter窗口
root = tk.Tk()
root.geometry("400x300")  # 设置宽度为400像素,高度为300像素
root.title("Image Viewer")

# 添加一个按钮来选择图片
def open_image():
    try:
        file_path = filedialog.askopenfilename()
        if file_path:
            image = Image.open(file_path)
            photo = ImageTk.PhotoImage(image)

            # 清除旧图片
            for widget in root.winfo_children():
                if isinstance(widget, tk.Label):
                    widget.destroy()
            
            label = tk.Label(root, image=photo)
            label.image = photo
            label.pack()

            # 调整窗口大小以适应图片
            root.geometry("{}x{}".format(image.width, image.height))
    except AttributeError:
        print("No image selected.")

button = tk.Button(root, text="Open Image", command=open_image)
button.pack()

# 运行窗口
root.mainloop()

This program creates a tkinter window, sets the window size to 400x300 pixels, and sets the window title to "Image Viewer".

Add a button. When the user clicks the button, a file selection dialog box will pop up and the user can select an image file.

After selecting a picture, the program will use the Image.open method in the PIL library to open the selected picture file and display it in the window.

The program displays the selected image in a window and clears old images when the user selects a new image.

In the example, a try-except block is used to catch FileNotFoundError, which is triggered when the user deselects an image. When the user deselects a picture, a message is printed to inform the user that no picture was selected. This will avoid errors caused by deselecting images.

2. Picture viewing program 1

The "Open Directory" button is used to specify a directory, and two more buttons are added to the form: "Previous Image" and "Next Image". Click these two buttons to switch the display of pictures in the specified directory. The three buttons are arranged horizontally at the top, with the image below. If the size of the selected picture exceeds the size of the window, the program will scale the picture to an appropriate size to fit the window. The renderings are as follows:

The source code is as follows:

import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import os

class ImageViewer:
    def __init__(self, root):
        self.root = root
        self.root.geometry("400x350")
        self.root.title("Image Viewer")

        self.image_dir = ""
        self.image_files = []
        self.current_index = 0

        # 创建顶部按钮框架
        self.button_frame = tk.Frame(self.root)
        self.button_frame.pack(side="top")

        # 创建打开目录按钮
        self.open_button = tk.Button(self.button_frame, text="Open Directory", command=self.open_directory)
        self.open_button.pack(side="left")

        # 创建上一张图片按钮
        self.prev_button = tk.Button(self.button_frame, text="Previous Image", command=self.show_previous_image)
        self.prev_button.pack(side="left")

        # 创建下一张图片按钮
        self.next_button = tk.Button(self.button_frame, text="Next Image", command=self.show_next_image)
        self.next_button.pack(side="left")

        # 创建图片显示区域
        self.image_label = tk.Label(self.root)
        self.image_label.pack()


    def open_directory(self):
        try:
            self.image_dir = filedialog.askdirectory()
            if self.image_dir:
                self.image_files = [f for f in os.listdir(self.image_dir) if f.endswith(".jpg") or f.endswith(".png") or f.endswith(".jfif")]
                self.current_index = 0
                self.show_image()
        except tk.TclError:
            print("No directory selected.")

    def show_image(self):
        if self.image_files:
            image_path = os.path.join(self.image_dir, self.image_files[self.current_index])
            image = Image.open(image_path)
            image.thumbnail((400, 300), Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(image)
            self.image_label.config(image=photo)
            self.image_label.image = photo

    def show_previous_image(self):
        if self.image_dir:
            if self.image_files:
                self.current_index = (self.current_index - 1) % len(self.image_files)
                self.show_image()
            else:
                print("Please open a directory first.")
        else:
            print("Please open a directory first.")

    def show_next_image(self):
        if self.image_dir:
            if self.image_files:
                self.current_index = (self.current_index + 1) % len(self.image_files)
                self.show_image()
            else:
                print("Please open a directory first.")
        else:
            print("Please open a directory first.")

root = tk.Tk()
app = ImageViewer(root)
root.mainloop()

3. Picture viewing program 2

There are three controls on the form, the list box and buttons are placed up and down on the left side of the form, the right area displays pictures, the "Open Directory" button is used to specify the directory, and the list is used to place all picture files in the specified directory. Name, click the image file name in the list, the image will be displayed on the form without deformation on the right side (the image will be scaled to the appropriate size to fit the window), the effect is as follows:

The source code is as follows:

import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import os

# 创建主窗口
root = tk.Tk()
root.geometry("600x300")
root.title("Image Viewer")

# 创建一个Frame来包含按钮和列表框
left_frame = tk.Frame(root)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, padx=5, pady=5)

# 创建一个Frame来包含图片显示区域
right_frame = tk.Frame(root)
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

# 创建一个列表框来显示文件名
listbox = tk.Listbox(left_frame)
listbox.pack(fill=tk.BOTH, expand=True)

# 创建一个滚动条并将其与列表框关联
scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar.config(command=listbox.yview)
listbox.config(yscrollcommand=scrollbar.set)

# 创建一个标签来显示图片
image_label = tk.Label(right_frame)
image_label.pack(fill=tk.BOTH, expand=True)

# 函数:打开目录并列出图片文件
def open_directory():
    directory = filedialog.askdirectory()
    if directory:
        # 清空列表框
        listbox.delete(0, tk.END)
        # 列出目录中的所有图片文件
        for file in os.listdir(directory):
            if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif','.jfif')):
                listbox.insert(tk.END, file)
        # 保存当前目录
        open_directory.current_directory = directory

# 函数:在右侧显示选中的图片
def show_selected_image(event):
    if not hasattr(open_directory, 'current_directory'):
        return
    # 获取选中的文件名
    selected_file = listbox.get(listbox.curselection())
    # 构建完整的文件路径
    file_path = os.path.join(open_directory.current_directory, selected_file)
    # 打开图片并进行缩放
    image = Image.open(file_path)
    image.thumbnail((right_frame.winfo_width(), right_frame.winfo_height()), Image.ANTIALIAS)
    # 用PIL的PhotoImage显示图片
    photo = ImageTk.PhotoImage(image)
    image_label.config(image=photo)
    image_label.image = photo  # 保存引用,防止被垃圾回收

# 创建“Open Directory”按钮
open_button = tk.Button(left_frame, text="Open Directory", command=open_directory)
open_button.pack(fill=tk.X)

# 绑定列表框选择事件
listbox.bind('<<ListboxSelect>>', show_selected_image)

# 运行主循环
root.mainloop()

appendix

More information about directories, folders and paths in the computer windows operating system can be foundhttps://blog.csdn.net/cnds123/article/details/105169800 a>

python file or folder operationhttps://blog.csdn.net/cnds123/article/details/123583020

Introduction to Python’s Tkinter package filedialog module https://blog.csdn.net/cnds123/article/details/134906506

Guess you like

Origin blog.csdn.net/cnds123/article/details/134891129