Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from PIL import Image, ImageTk
- import glob
- def insertfiles():
- for filename in glob.glob("*.png"):
- lst.insert(tk.END, filename)
- for filename in glob.glob("*.jpg"):
- lst.insert(tk.END, filename)
- def showimg(event):
- n = lst.curselection()
- if n:
- filename = lst.get(n[0])
- img = Image.open(filename)
- w_img, h_img = img.size
- # Get the dimensions of the window
- w_win = root.winfo_width()
- h_win = root.winfo_height()
- # Calculate the aspect ratio of the image and window
- aspect_ratio_img = w_img / h_img
- aspect_ratio_win = w_win / h_win
- if aspect_ratio_img > aspect_ratio_win:
- # Scale the image based on width
- new_w = w_win
- new_h = int(w_win / aspect_ratio_img)
- else:
- # Scale the image based on height
- new_h = h_win
- new_w = int(h_win * aspect_ratio_img)
- img = img.resize((new_w, new_h), Image.LANCZOS) # Use LANCZOS for resampling
- photo = ImageTk.PhotoImage(img)
- canvas.config(width=new_w, height=new_h)
- canvas.create_image(0, 0, image=photo, anchor=tk.NW)
- canvas.image = photo
- root = tk.Tk()
- root.geometry("800x600+300+50")
- # Create a frame to hold the listbox and scrollbar
- frame = tk.Frame(root)
- frame.pack(side="left", fill="y")
- # Create a vertical scrollbar
- scrollbar = tk.Scrollbar(frame, orient="vertical")
- # Create the listbox with the scrollbar attached
- lst = tk.Listbox(frame, width=15, yscrollcommand=scrollbar.set)
- scrollbar.config(command=lst.yview)
- # Pack the listbox and scrollbar
- lst.pack(side="left", fill="both", expand=True)
- scrollbar.pack(side="right", fill="y")
- lst.bind("<<ListboxSelect>>", showimg)
- insertfiles()
- canvas = tk.Canvas(root)
- canvas.pack(fill=tk.BOTH, expand=True)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement