欢迎访问宙启技术站
智能推送

用Python实现的简单图片浏览器程序

发布时间:2023-12-04 10:36:29

下面是一个使用Python实现的简单图片浏览器程序的例子:

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

class ImageViewer:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("图片浏览器")
        self.images = []
        self.current_image_index = 0

        self.create_widgets()

    def create_widgets(self):
        self.canvas = tk.Canvas(self.root, width=500, height=500)
        self.canvas.pack()

        self.button_frame = tk.Frame(self.root)
        self.button_frame.pack()

        self.prev_button = tk.Button(self.button_frame, text="上一张", command=self.show_prev_image)
        self.prev_button.pack(side=tk.LEFT)

        self.next_button = tk.Button(self.button_frame, text="下一张", command=self.show_next_image)
        self.next_button.pack(side=tk.LEFT)

        self.open_button = tk.Button(self.button_frame, text="打开图片", command=self.open_image)
        self.open_button.pack(side=tk.LEFT)

    def open_image(self):
        filetypes = (
            ("JPEG files", "*.jpg"),
            ("PNG files", "*.png"),
            ("All files", "*.*")
        )
        path = filedialog.askopenfilename(filetypes=filetypes)
        if path:
            self.images = self.get_image_files(os.path.dirname(path))
            self.current_image_index = self.images.index(path)
            self.show_image(path)

    def get_image_files(self, directory):
        image_files = []
        for file in os.listdir(directory):
            if file.endswith(".jpg") or file.endswith(".png"):
                image_files.append(os.path.join(directory, file))
        return image_files

    def show_image(self, path):
        image = Image.open(path)
        image.thumbnail((500, 500))
        self.canvas.image = tk.PhotoImage(image)
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.canvas.image)

    def show_prev_image(self):
        if self.current_image_index > 0:
            self.current_image_index -= 1
            self.show_image(self.images[self.current_image_index])

    def show_next_image(self):
        if self.current_image_index < len(self.images) - 1:
            self.current_image_index += 1
            self.show_image(self.images[self.current_image_index])

    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    image_viewer = ImageViewer()
    image_viewer.run()

这个程序使用Pillow库来操作图像,使用tkinter库来创建用户界面。程序实现了一个简单的图片浏览器,用户可以打开图片文件夹,然后通过点击按钮来切换到上一张或下一张图片。

使用该程序的方法是,首先创建一个ImageViewer对象,并调用其run()方法来运行程序。然后,程序界面上会显示一个空白的画布和三个按钮,分别是"上一张"、"下一张"和"打开图片"。点击"打开图片"按钮时,弹出一个文件选择对话框让用户选择图片。选择完图片后,程序会获取图片所在文件夹的路径,并获取该文件夹下所有的图片文件。然后将当前选择的图片显示在画布上。用户可以点击"上一张"或"下一张"按钮来切换到其他图片进行浏览。

这个示例程序较为简单,只实现了基本的图片浏览功能。可以根据需要进行扩展,比如添加图片缩放、旋转或删除功能等。