首页 > 其他分享 >***看图器终极版

***看图器终极版

时间:2024-05-17 14:41:39浏览次数:11  
标签:终极版 index 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_path = self.all_images[folder_index][image_index]
            image = Image.open(image_path)

            # 获取窗口大小
            window_width = self.winfo_width()
            window_height = self.winfo_height()

            # 计算适合窗口的缩放比例
            scale_w = min(window_width / image.width, 1)
            scale_h = min(window_height / image.height, 1)
            scale = min(scale_w, scale_h, 1)  # 保证图片不被放大

            # 确保图片的最长边不超过1000像素
            max_length = 1000
            if max(image.width, image.height) * scale > max_length:
                scale = max_length / max(image.width, image.height)

            # 调整图片大小
            new_width = int(image.width * scale)
            new_height = int(image.height * scale)
            image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
            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
        elif self.current_image_index == len(self.all_images[self.current_folder_index]):
            self.current_image_index -= 1  # Move to the last image in the current folder if we deleted the last image
        self.show_image(self.current_folder_index, self.current_image_index)

    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
        def find_leaf_folders(folder_path):
            is_leaf = True
            for entry in os.listdir(folder_path):
                full_path = os.path.join(folder_path, entry)
                if os.path.isdir(full_path):
                    is_leaf = False
                    find_leaf_folders(full_path)
            if is_leaf:
                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)
        find_leaf_folders(base_folder)
        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,self,current,看图器,images,folder,image
From: https://www.cnblogs.com/zly324/p/18197743

相关文章

  • webrtc终极版(三)将官方的demo部署到自己的服务器中
    webrtc终极版(三)将官方的demo部署到自己的服务器中本节,我们详细介绍下,如何再本地搭建RTCMultiConnection服务目录webrtc终极版(三)将官方的demo部署到自己的服务器中前言一、安装步骤1.下载并解压文件2.使用npm安装总结前言webrtc终极版系列,再年前,写了前两篇,还剩下两篇没有写,......
  • webrtc终极版(二)搭建自己的iceserver服务,并用到RTCMultiConnection的demo中
    webrtc终极版(二)搭建自己的iceserver服务,并用到RTCMultiConnection的demo中目录webrtc终极版(二)搭建自己的iceserver服务,并用到RTCMultiConnection的demo中前言一、stunserver,turnserver,iceserver是什么?二、具体搭建步骤1.下载安装coturn2、处理证书问题3、处理各个ip以及端口的配......
  • webrtc终极版(题外话)辛苦写文章分享,竟然遇到喷子狂喷,写篇文章回怼下,顺便发表下面对喷子
    webrtc终极版(题外话)辛苦写文章分享,竟然遇到喷子狂喷,写篇文章回怼下,顺便发表下面对喷子的处理方式第一篇文章发过后,出人意料的是,收到了博客园某一位用户的狂喷【注:本系列文章会同步发布到csdn、博客园、稀土掘金等平台上】,如下图示图片可能不清楚,我再把这位喷子的原话粘贴下来:......
  • webrtc终极版(一)5分钟搭建多人实时会议系统webrtc
    webrtc终极版(一),支持https,在线部署【不是本地demo】,采用RTCMultiConnection官方demo,5分钟即可搭建成功@目录webrtc终极版(一),支持https,在线部署【不是本地demo】,采用RTCMultiConnection官方demo,5分钟即可搭建成功前言一、webrtc是什么?二、搭建demo步骤1.代码内容2.运行效果总结前......
  • 【网工玩转自动化】深入浅出TextFSM 2022终极版
    《从零开始NetDevOps》是本人8年多的NetDevOps实战总结的一本书(且称之为书,通过公众号连载的方式,集结成册,希望有天能以实体书的方式和大家相见)。NetDevOps是指以网络工程师为主体,针对网络运维场景进行自动化开发的工作思路与模式,是2014年左右从国外刮起来的一股“网工学Python"的风......
  • java实现一组数据计算同比环比(终极版)
    本篇基于下面两篇博客的内容整合实现:java实现一组数据计算同比环比CGLIB基于一个已有类动态生成一个子类bean(转)之前的博客中已经捋清了在只有日期和一列数据的情况下动......
  • AcCoders 10665:【省选基础 模拟】魔兽世界终极版 题解
    一句话,大模拟,对着题意敲就完了。干就完了,奥利给!正正好好618行~//10665ProblemG:【省选基础模拟】魔兽世界终极版#include<iostream>#include<cstdio>#include......
  • 阿里巴巴Java开发手册(终极版) pdf
    高清扫描版下载链接:https://pan.baidu.com/s/1H40dGfVJkJdmVHeiLLuIjw点击这里获取提取码 ......