Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import filedialog
- from PIL import Image, ImageTk
- import glob
- def insertfiles(folder):
- for filename in glob.glob(folder + "/*.png"):
- lst.insert(tk.END, filename)
- for filename in glob.glob(folder + "/*.jpg"):
- lst.insert(tk.END, filename)
- for filename in glob.glob(folder + "/*.bmp"):
- 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
- def browse_folder():
- folder_selected = filedialog.askdirectory()
- if folder_selected:
- lst.delete(0, tk.END) # Clear the listbox
- insertfiles(folder_selected)
- root = tk.Tk()
- root.title("NAJEEB IMAGE VIEWER")
- #root.configure(bg="Green") # set background color
- 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)
- # Insert files from the selected folder
- insertfiles(".")
- # Add a button to browse for a folder
- browse_button = tk.Button(root, text="Browse Folder", command=browse_folder)
- browse_button.pack()
- canvas = tk.Canvas(root)
- canvas.pack(fill=tk.BOTH, expand=True)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement