Python实现GUI图片浏览程序

Python实现GUI图片浏览程序

下面程序需要pillow库。pillow是 Python 的第三方图像处理库,需要安装才能实用。pillow是PIL( Python Imaging Library)基础上发展起来的,需要注意的是pillow库安装用pip install pillow,导包时要用PIL来导入。更多情况可见https://blog.csdn.net/cnds123/article/details/126141838

一、简单的图片查看程序

功能,使用了tkinter库来创建一个窗口,用户可以通过该窗口选择一张图片并在窗口中显示。能调整窗口大小以适应图片。效果图如下:

源码如下:

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()

此程序,创建一个tkinter窗口,设置窗口的大小为400x300像素,并设置窗口标题为"Image Viewer"。

添加一个按钮,当用户点击该按钮时,会弹出文件选择对话框,用户可以选择一张图片文件。

选择图片后,程序会使用PIL库中的Image.open方法打开所选的图片文件,并将其显示在窗口中。

程序会在窗口中显示所选的图片,并在用户选择新图片时清除旧图片。

示例中,使用try-except块来捕获FileNotFoundError,该错误会在用户取消选择图片时触发。当用户取消选择图片时,会打印一条消息提示用户没有选择图片。这样就可以避免因为取消选择图片而导致的报错。

二、图片查看程序1

“Open Directory”按钮用于指定一个目录,窗体上再添加两个按钮:“Previous Image” 和“Next Image”,单击这两个按钮实现切换显示指定目录中的图片。这三个按钮水平排列在顶部,在下方显示图片。如果所选图片的尺寸超过了窗口的大小,程序会将图片缩放到合适的尺寸以适应窗口。效果图如下:

源码如下:

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()

三、图片查看程序2

窗体上有3个控件,列表框和按钮和在窗体上左侧上下放置,右侧区域显示图片, “Open Directory”按钮用于指定目录中,列表用于放置指定目录中的所有图片文件名,点击列表中的图片文件名,图片在右侧不变形缩放显示到窗体上(图片缩放到合适的尺寸以适应窗口),效果图如下:

源码如下:

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()

附录

关于计算机windows操作系统中的目录、文件夹 、路径更多情况可见https://blog.csdn.net/cnds123/article/details/105169800

python文件或文件夹操作https://blog.csdn.net/cnds123/article/details/123583020

Python的Tkinter包filedialog模块介绍 https://blog.csdn.net/cnds123/article/details/134906506

猜你喜欢

转载自blog.csdn.net/cnds123/article/details/134891129