首页 > 编程语言 >***python看图软件***(+-切换文件夹,d删除所在文件夹)

***python看图软件***(+-切换文件夹,d删除所在文件夹)

时间:2024-03-18 16:34:15浏览次数:25  
标签:index python self +- current 文件夹 images folder image

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

        # 初始化变量
        self.all_images = []
        self.current_folder_index = 0
        self.current_image_index = 0
        self.total_image_count = 0

        # 设置背景为黑色
        self.configure(bg='black')

        # 设置图片计数器(放置在左上角)
        self.counter_label = tk.Label(self, text="", fg="white", bg="black", anchor="nw")
        self.counter_label.pack(side='top', anchor='nw', padx=10, pady=10)

        # 新增:显示当前文件夹名称的标签
        self.folder_name_label = tk.Label(self, text="", fg="white", bg="black", anchor="nw")
        self.folder_name_label.pack(side='top', anchor='nw', padx=10, pady=30)

        # 设置图片标签
        self.img_label = tk.Label(self, bg='black')
        self.img_label.pack(expand=True)

        # 全屏设置
        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('<d>', self.delete_folder)  # 绑定d键以删除当前文件夹
        self.bind('<Double-1>', self.toggle_fullscreen)

        # 新增:绑定 "-" 和 "+" 键以快速切换文件夹
        self.bind('-', lambda e: self.switch_folder(-1))
        self.bind('+', lambda e: self.switch_folder(1))

        # 从文件夹加载图片
        self.load_images()

    def switch_folder(self, direction):
        new_folder_index = self.current_folder_index + direction
        if 0 <= new_folder_index < len(self.all_images):
            self.current_folder_index = new_folder_index
            self.current_image_index = 0  # 始终设置为第一张图片
            self.show_image(self.current_folder_index, self.current_image_index)
        else:
            messagebox.showinfo("Info", "No more folders in this direction.")

    def update_counter(self):
        current_position = sum(len(folder) for folder in self.all_images[:self.current_folder_index]) + self.current_image_index + 1
        self.counter_label.config(text=f"{current_position}/{self.total_image_count}")

    def update_folder_name(self):
        folder_name = os.path.basename(os.path.dirname(self.all_images[self.current_folder_index][0]))
        self.folder_name_label.config(text=f"Folder: {folder_name}")

    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
            self.update_counter()
            self.update_folder_name()
        else:
            messagebox.showinfo("Info", "No more images in this direction.")

    def show_next_image(self, event=None):
        if self.current_image_index < len(self.all_images[self.current_folder_index]) - 1:
            self.current_image_index += 1
        else:
            self.switch_folder(1)
        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.current_image_index -= 1
        else:
            self.switch_folder(-1)
            if self.current_folder_index < len(self.all_images):
                # 移至新文件夹的最后一张图片
                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]
        self.total_image_count -= 1
        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 delete_folder(self, event=None):
        # 获取当前图片所在的文件夹路径
        current_folder_path = os.path.dirname(self.all_images[self.current_folder_index][self.current_image_index])

        # 弹出确认删除的对话框
        if messagebox.askyesno("Delete Folder", "Are you sure you want to delete the current folder and all its contents?"):
            # 删除文件夹及其所有内容
            for root, dirs, files in os.walk(current_folder_path, topdown=False):
                for name in files:
                    os.remove(os.path.join(root, name))
                for name in dirs:
                    os.rmdir(os.path.join(root, name))
            os.rmdir(current_folder_path)

            # 从图片列表中删除该文件夹下的所有图片
            del self.all_images[self.current_folder_index]
            self.total_image_count -= len(self.all_images[self.current_folder_index])

            # 检查是否还有剩余的文件夹
            if len(self.all_images) > 0:
                # 尝试显示下一个文件夹的第一张图片
                if self.current_folder_index < len(self.all_images):
                    self.current_image_index = 0
                else:
                    # 如果已经是最后一个文件夹,则回退到上一个文件夹的第一张图片
                    self.current_folder_index = max(0, len(self.all_images) - 1)
                    self.current_image_index = 0
                self.show_image(self.current_folder_index, self.current_image_index)
            else:
                self.quit()

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

    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)
                    self.total_image_count += len(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()

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

标签:index,python,self,+-,current,文件夹,images,folder,image
From: https://www.cnblogs.com/zly324/p/18080695

相关文章

  • Python性能测试框架Locust
    Locust是一个比较容易上手的分布式用户负载测试工具。它旨在对网站(或其他系统)进行负载测试,并确定系统可以处理多少个并发用户,Locust在英文中是蝗虫的意思:作者的想法是在测试期间,放一大群蝗虫攻击您的网站。当然事先是可以用Locust定义每个蝗虫(或测试用户)的行为,并且通过Web......
  • Python3 使用 sqlcipher 来增强本地数据的安全性
    使用sqlcipher来增强本地数据的安全性本文是基于系列文章PyQt5+SQLAlchemy做登录注册页的补充,并不单独放在系列文中,主要讲的是,使用sqlcipher来保存本地密码,这比直接使用SQLite更安全关于sqlcipher,官方介绍原文如下:SQLCipherisastandaloneforkoftheSQLitedata......
  • openGauss数据库之Python驱动快速入门
    OpenGauss数据库之Python驱动openGauss是一款开源关系型数据库管理系统,采用木兰宽松许可证v2发行。openGauss内核源自PostgreSQL,深度融合华为在数据库领域多年的经验,结合企业级场景需求,持续构建竞争力特性。可是目前针对于OpenGauss数据库的Python应用程序的开发少......
  • python安装模块的方式
    使用pip(在线)方式安装piplist//用于显示当前安装的所有模块和版本,pip本身也是一个模块1)若pip不存在则python-mensurepip//确保pip可用2)更新pippipinstall--upgradepip//更新pip3)安装包,以numpy为例python-mpipuninstallnumpy//卸载numpypython-mpipi......
  • Python 查找PDF中的指定文本并高亮显示
    在处理大量PDF文档时,有时我们需要快速找到特定的文本信息。本文将提供以下三个Python示例来帮助你在PDF文件中快速查找并高亮指定的文本。查找并高亮PDF中所有的指定文本查找并高亮PDF某个区域内的指定文本使用正则表达式搜索指定文本并高亮 本文将用到国产第三方库-Spi......
  • python命令行参数
    python帮助文档Launcherarguments:-2:LaunchthelatestPython2.xversion-3:LaunchthelatestPython3.xversion-X.Y:LaunchthespecifiedPythonversionTheabovedefaulttoanarchitecturenativeruntime,butwillselectanyavailable.Ad......
  • Python中那些简单又好用的特性和用法
    Python中那些简单又好用的特性和用法Python作为我的主力语言帮助我开发了许多DevOps运维自动化系统,这篇文章总结几个我在编写Python代码过程中用到的几个简单又好用的特性和用法,这些特性和用法可以帮助我们更高效地编写Python代码1.链式比较x=5y=10z=15ifx<y<z......
  • python 面向对象(三)magic methods
    magicmethods就是双下划线方法AsaPythondeveloperwhowantstoharnessthepowerofobject-orientedprogramming,you’lllovetolearnhowtocustomizeyourclassesusingspecialmethods,alsoknownasmagicmethodsordundermethods.Aspecialmethodisa......
  • Python实现HTTPS网站证书过期监控及更新
    Python实现HTTPS网站证书过期监控及更新当前HTTP逐渐被大众所抛弃,HTTPS正在成为互联网上的主流。前段时间我们维护的一个HTTPS证书即将过期,由于多云环境比较复杂,团队小伙伴在替换更新证书的过程中出现疏漏,导致有一个域名证书没有及时更新,影响了系统可用性,为了杜绝这种问题再次发......
  • python + xlwings 操作Excel,复制粘贴保留格式
    在使用python处理Excel时,需求是要保留Excel内的格式(例如字体,大小,背景颜色,函数公式....),试了其它几个库,都没达到效果,偶然发现了xlwings,可以达到我所需要的效果。importxlwingsasxwfromxlwings.constantsimportPasteType打开Excel文件workbook=xw.Book('example.xlsx')......