Advertisement
Najeebsk

PICTURE-VIEWER.py

Feb 25th, 2024
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. import tkinter as tk
  2. from PIL import Image, ImageTk
  3. import glob
  4.  
  5. def insertfiles():
  6.     for filename in glob.glob("*.png"):
  7.         lst.insert(tk.END, filename)
  8.     for filename in glob.glob("*.jpg"):
  9.         lst.insert(tk.END, filename)
  10.  
  11. def showimg(event):
  12.     n = lst.curselection()
  13.     if n:
  14.         filename = lst.get(n[0])
  15.         img = Image.open(filename)
  16.         w_img, h_img = img.size
  17.        
  18.         # Get the dimensions of the window
  19.         w_win = root.winfo_width()
  20.         h_win = root.winfo_height()
  21.        
  22.         # Calculate the aspect ratio of the image and window
  23.         aspect_ratio_img = w_img / h_img
  24.         aspect_ratio_win = w_win / h_win
  25.        
  26.         if aspect_ratio_img > aspect_ratio_win:
  27.             # Scale the image based on width
  28.             new_w = w_win
  29.             new_h = int(w_win / aspect_ratio_img)
  30.         else:
  31.             # Scale the image based on height
  32.             new_h = h_win
  33.             new_w = int(h_win * aspect_ratio_img)
  34.        
  35.         img = img.resize((new_w, new_h), Image.LANCZOS)  # Use LANCZOS for resampling
  36.         photo = ImageTk.PhotoImage(img)
  37.         canvas.config(width=new_w, height=new_h)
  38.         canvas.create_image(0, 0, image=photo, anchor=tk.NW)
  39.         canvas.image = photo
  40.  
  41. root = tk.Tk()
  42. root.geometry("800x600+300+50")
  43.  
  44. # Create a frame to hold the listbox and scrollbar
  45. frame = tk.Frame(root)
  46. frame.pack(side="left", fill="y")
  47.  
  48. # Create a vertical scrollbar
  49. scrollbar = tk.Scrollbar(frame, orient="vertical")
  50.  
  51. # Create the listbox with the scrollbar attached
  52. lst = tk.Listbox(frame, width=15, yscrollcommand=scrollbar.set)
  53. scrollbar.config(command=lst.yview)
  54.  
  55. # Pack the listbox and scrollbar
  56. lst.pack(side="left", fill="both", expand=True)
  57. scrollbar.pack(side="right", fill="y")
  58.  
  59. lst.bind("<<ListboxSelect>>", showimg)
  60. insertfiles()
  61. canvas = tk.Canvas(root)
  62. canvas.pack(fill=tk.BOTH, expand=True)
  63.  
  64. root.mainloop()
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement