Home > Enterprise >  Tkinter Multiple Image Viewer within Frame
Tkinter Multiple Image Viewer within Frame

Time:08-31

I would like to make a window construction for a photo previewer. I am stuck. My code doesn't work. I made a frame hierarchy shown below. I would like to show thumbnails in the thumbnail frame. enter image description here

# TODO 0: IMPORT REQUIRED LIBRARIES AND MODULES
from tkinter import *
from PIL import Image, ImageTk


# TODO 1: CREATE A CLASS
class EditScreen:
    def __init__(self, file_directory_list):
        self.edit_window_init()
        self.file_directory_list = file_directory_list
        self.display_selected_images()
        self.edit_window.mainloop()

# TODO 2: CREATE A NEW EDIT SCREEN
    def edit_window_init(self):
        self.edit_window = Toplevel()
        self.edit_window.title("Edit")
        self.edit_window.geometry('1200x800')
        self.background_color = "#F8F1F1"
        self.my_font_color = "#0A065D"
        self.my_font = 'Poppins'

# TODO 3: DISPLAY SELECTED IMAGES IN THIS SCREEN
    def display_selected_images(self):
        thumbnail_frame = Frame(self.edit_window, height=1200, width=300)
        thumbnail_frame.pack(side='left')
        thumbnail_frame_canvas= Canvas(master=thumbnail_frame)
        thumbnail_frame_canvas.place(x=0,y=0)
# TODO 3.1: PUT ALL SELECTED IMAGES THUMBNAIL TO LEFT HAND SIDE OF THE EDIT SCREEN
        for selected_image_directory in self.file_directory_list:
            print(self.file_directory_list.index(selected_image_directory))
            selected_image = ImageTk.PhotoImage(file=selected_image_directory)
            selected_image_location = thumbnail_frame_canvas.create_image((30,30),image=selected_image)
            selected_image_location.pack()
            #.grid(row=self.file_directory_list.index(selected_image_directory),column=0)

CodePudding user response:

Consider these lines of code:

selected_image_location = thumbnail_frame_canvas.create_image((30,30),image=selected_image)
selected_image_location.pack()

create_image is documented to return an integer, which is an internal id of the canvas object that was created. You then try to call pack on that integer, but integers don't have a pack method. You need to remove the call to pack

Another problem was mentioned in a comment to your question: you're not saving a reference to the image, so it's going to get destroyed by python's garbage collector.

You can save a reference by using a global list, and appending the images to that list:

def display_selected_images(self):
    global selected_images
    ...
    selected_images = []
    for selected_image_directory in self.file_directory_list:
        ...
        selected_image = ImageTk.PhotoImage(file=selected_image_directory)
        selected_images.append(selected_image)
        ...
  • Related