首页 > 编程语言 >Python 图像查看器

Python 图像查看器

时间:2024-01-18 10:56:07浏览次数:34  
标签:index 查看器 Python self current 图像 images folder image


当然,这里是一个简洁而全面的介绍,适合用于在博客中介绍这个图像查看器程序:


Python 图像查看器

在这篇博客中,我将向大家介绍一个由我开发的简单但功能强大的图像查看器。这个图像查看器是用Python编写的,利用了Tkinter图形用户界面库来提供直观的用户体验。它不仅可以浏览单个文件夹中的图片,还能遍历包含多个子文件夹的复杂文件夹结构,并逐个显示每个子文件夹中的图片。

主要功能

  1. 遍历子文件夹: 用户可以指定一个包含多个子文件夹的总文件夹。程序将自动进入每个子文件夹并显示其中的图片。

  2. 全屏显示: 双击任意图片,可以在全屏模式下查看。

  3. 键盘导航: 使用键盘的左右箭头键可以在图片之间前后切换。按下 Delete 键可以删除当前显示的图片。

  4. 智能提示: 当用户查看完一个子文件夹中的所有图片后,程序会显示提示信息。在最后一个文件夹的最后一张图片后,会出现结束提示。

  5. 容错处理: 程序能够处理空的子文件夹或子文件夹中的非图像文件,自动跳过它们,确保用户体验的连贯性和程序的稳定性。

技术细节

  • 开发语言: Python
  • 图形界面库: Tkinter
  • 图像处理: Pillow库用于加载和显示图片

使用方法

用户启动程序后,会被要求输入一个包含图片的总文件夹路径。程序接着开始从第一个子文件夹的第一张图片进行显示。用户可以通过键盘操作在图片间切换,或删除当前显示的图片。当遍历完一个子文件夹后,会收到提示,并可以继续浏览下一个子文件夹的图片。

import os
import tkinter as tk
from tkinter import simpledialog, messagebox
from PIL import Image, ImageTk

class ImageViewer(tk.Tk):
    def __init__(self):
        super().__init__()

        # Initialize variables
        self.all_images = []
        self.current_folder_index = 0
        self.current_image_index = 0
        self.img_label = tk.Label(self)
        self.img_label.pack(expand=True)

        # Full screen setup
        self.attributes('-fullscreen', True)
        self.bind('<Escape>', lambda e: self.quit())
        self.bind('<Left>', self.show_prev_image)
        self.bind('<Right>', self.show_next_image)
        self.bind('<Delete>', self.delete_image)
        self.bind('<Double-1>', self.toggle_fullscreen)

        # Load images from folders
        self.load_images()

    def load_images(self):
        base_folder = simpledialog.askstring("Input", "Enter the path of the base folder:")
        if not base_folder or not os.path.isdir(base_folder):
            messagebox.showerror("Error", "Invalid folder path.")
            self.quit()
            return

        for folder in sorted(os.listdir(base_folder)):
            folder_path = os.path.join(base_folder, folder)
            if os.path.isdir(folder_path):
                images = [os.path.join(folder_path, file) for file in os.listdir(folder_path)
                          if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
                if images:
                    self.all_images.append(images)

        if self.all_images:
            self.show_image(self.current_folder_index, self.current_image_index)
        else:
            messagebox.showinfo("No Images", "No images found in the provided folder structure.")
            self.quit()

    def show_image(self, folder_index, image_index):
        if folder_index < len(self.all_images) and image_index < len(self.all_images[folder_index]):
            self.current_image_index = image_index
            self.current_folder_index = folder_index
            image = Image.open(self.all_images[folder_index][image_index])
            photo = ImageTk.PhotoImage(image)
            self.img_label.config(image=photo)
            self.img_label.image = photo
        elif folder_index < len(self.all_images):
            messagebox.showinfo("End of Folder", "End of current folder. Press 'Right' to go to the next folder.")
        else:
            messagebox.showinfo("End of Gallery", "You have reached the end of the gallery.")
            self.quit()

    def show_next_image(self, event=None):
        if self.current_image_index < len(self.all_images[self.current_folder_index]) - 1:
            self.show_image(self.current_folder_index, self.current_image_index + 1)
        elif self.current_folder_index < len(self.all_images) - 1:
            self.current_folder_index += 1
            self.current_image_index = 0
            self.show_image(self.current_folder_index, self.current_image_index)

    def show_prev_image(self, event=None):
        if self.current_image_index > 0:
            self.show_image(self.current_folder_index, self.current_image_index - 1)
        elif self.current_folder_index > 0:
            self.current_folder_index -= 1
            self.current_image_index = len(self.all_images[self.current_folder_index]) - 1
            self.show_image(self.current_folder_index, self.current_image_index)

    def delete_image(self, event=None):
        current_image_path = self.all_images[self.current_folder_index][self.current_image_index]
        os.remove(current_image_path)
        del self.all_images[self.current_folder_index][self.current_image_index]
        if len(self.all_images[self.current_folder_index]) == 0:
            del self.all_images[self.current_folder_index]
            if self.current_folder_index >= len(self.all_images):
                self.quit()
                return
        self.show_next_image()

    def toggle_fullscreen(self, event=None):
        self.attributes('-fullscreen', not self.attributes('-fullscreen'))

if __name__ == "__main__":
    app = ImageViewer()
    app.mainloop()

 

标签:index,查看器,Python,self,current,图像,images,folder,image
From: https://www.cnblogs.com/zly324/p/17972042

相关文章

  • 【Python】解压压缩包(处理中文乱码问题)
    支持中文编码fromzipfileimportZipFiledefsupport_gbk(zip_file):name_to_info=zip_file.NameToInfo#copymapfirstforname,infoinname_to_info.copy().items():real_name=name.encode('cp437').decode('gbk')......
  • 使用pyinstaller打包python程序时报错UPX is not available
    使用pyinstaller打包python代码程序时报错:UPXisnotavailable原因是 python环境的Scripts文件夹内缺少了一个upx.exe的文件到官网https://github.com/upx/upx/releases/tag/v4.2.2中下载一个UPX,将下载文件解压后得到的upx.exe文件(解压后的所有文件里只要这一个文件即可,......
  • Python爬取B站视频 抓包过程分享
    B站对于很多人来说并不陌生,对于经常玩电脑的人来说,每天逛一逛B站受益匪浅。里面不仅有各种各样的知识库,就连很多游戏攻略啥的都有,真的是想要啥有啥。这么好用的平台得好好利用下。今天我将写一个爬虫程序专门抓取B站的视频,并且贴上详细的抓包过程。首先,我们需要安装requests库来发......
  • python 百分号输出
    python使用format()方法num=5print("{:.0%}".format(num/100))使用f-string需要python3.6以上版本num=5print(f"{num/100:.0%}")......
  • python创建httpserver,并处理get、post请求
    搭建一个简单的httpserver,用于测试数据通讯fromhttp.serverimportHTTPServer,BaseHTTPRequestHandlerimportjsondata={'result':'thisisatest'}host=('localhost',8888)classResquest(BaseHTTPRequestHandler):  defdo_GET(self):   ......
  • Python Matplotlib 实现基础绘图
    ​ 1、Matplotlib的三层结构Matplotlib是一个用于在Python中创建二维图表的库。为了更好地理解和使用Matplotlib,重要的是要了解其三层结构:容器层(ContainerLayer)、辅助显示层(HelperLayer)和图像层(ArtistLayer)。这些层级构成了Matplotlib的绘图体系结构。1)容器层(Conta......
  • stable Diffusion python 运行时抛出一个异常
    Python中的异常处理引言在编程过程中,我们经常会遇到各种错误和异常情况。为了提高程序的稳定性和可靠性,我们需要对这些异常情况进行处理。在Python中,异常处理是一个非常重要且常用的功能。异常的概念异常是程序中不正常的情况,例如:文件不存在、数组越界、除零错误等。当异常发生......
  • stable diffusion 运行时python意外退出 mac
    StableDiffusion运行时Python意外退出Mac实现指南简介在开发过程中,我们经常会遇到Python运行时意外退出的情况。这可能是由于代码错误、内存不足、依赖问题等原因导致的。本文将指导你如何在Mac系统上实现StableDiffusion运行时Python意外退出的解决方案。整体流......
  • LLaMA如何使用python调用
    使用Python调用LLaMA解决图像分类问题介绍LLaMA(LowLatencyModelAnalyzer)是一个用于分析和优化机器学习模型的开源工具。它可以帮助开发者在低延迟的环境中运行模型,并提供优化建议。本文将介绍如何使用Python调用LLaMA来解决一个具体的问题——图像分类。问题描述假设我们有......
  • stable diffusion python运行时抛出了一个异常
    实现“stablediffusionpython运行时抛出了一个异常”介绍在Python开发过程中,我们经常会遇到运行时抛出异常的情况。异常是程序在执行过程中发生的错误,如果不加以处理,就会导致程序终止或产生意想不到的结果。本文将教会你如何在Python中处理异常,并实现“stablediffusionpython......