|
本帖最后由 batche 于 2023-6-28 16:12 编辑
临时需要,写了一个简单的图片缩略图查看程序,在这里分享出来
- import os
- from PIL import Image, ImageTk
- import Tkinter
- import tkFileDialog
- folder_path = os.path.join(os.path.expanduser('~'), 'Pictures')
- window = Tkinter.Tk()
- window.title("Thumbnail Viewer-wuyou@batche-" + folder_path)
- window.geometry("580x300")
- canvas = Tkinter.Canvas(window, borderwidth=0, highlightthickness=0)
- scrollbar = Tkinter.Scrollbar(window, orient="vertical", command=canvas.yview)
- canvas.configure(yscrollcommand=scrollbar.set)
- scrollbar.pack(side="right", fill="y")
- canvas.pack(side="left", fill="both", expand=True)
- frame = Tkinter.Frame(canvas)
- canvas.create_window((0, 0), window=frame, anchor="nw")
- thumbnail_labels = []
- def reload_thumbnails():
- for label in thumbnail_labels:
- label.grid_forget()
- del thumbnail_labels[:]
- row = 0
- col = 0
- for filename in os.listdir(folder_path):
- if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".gif") or filename.endswith(".bmp") or filename.endswith(".webp") or filename.endswith(".jfif"):
- image = Image.open(os.path.join(folder_path, filename))
- thumbnail_image = image.copy()
- thumbnail_image.thumbnail((100, 100), Image.LANCZOS)
- thumbnail_tk = ImageTk.PhotoImage(thumbnail_image)
- thumbnail_label = Tkinter.Label(frame, image=thumbnail_tk)
- thumbnail_label.image = thumbnail_tk
- thumbnail_labels.append(thumbnail_label)
- thumbnail_label.bind("<Double-Button-1>", lambda event, filename=filename: open_image(os.path.join(folder_path, filename)))
- thumbnail_label.grid(row=row, column=col, padx=5, pady=5)
- col += 1
- if col == 5:
- row += 1
- col = 0
- frame.update_idletasks()
- canvas.configure(scrollregion=canvas.bbox("all"))
- def open_image(filename):
- image = Image.open(filename)
- image.show()
- def choose_folder():
- global folder_path
- folder_path = tkFileDialog.askdirectory()
- window.title("Thumbnail Viewer - " + folder_path)
- reload_thumbnails()
- menu_bar = Tkinter.Menu(window)
- window.config(menu=menu_bar)
- file_menu = Tkinter.Menu(menu_bar, tearoff=0)
- menu_bar.add_cascade(label="change folder", menu=file_menu)
- file_menu.add_command(label="Select Folder", command=choose_folder)
- file_menu.add_separator()
- file_menu.add_command(label="Exit", command=window.quit)
- reload_thumbnails()
- def on_mousewheel(event):
- canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
- canvas.bind_all("<MouseWheel>", on_mousewheel)
- window.mainloop()
复制代码
程序及源码链接:pan.baidu.com/s/10xJivEswDHjexMGYx8s7gQ?pwd=r38m
|
|