***python看圖軟體***(+-切換資料夾,d刪除所在資料夾)

不上火星不改名發表於2024-03-18
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()

相關文章