[Python] Tkinter canvas image probably being garbage collected but creating a persistent...

Discussão em 'Python' iniciado por Stack, Agosto 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a password manager program in python using tkinter. In my main.py, I have the code for the buttons which launch the add/update/retrieve windows. At present the code for these features are defined as functions in my main.py itself.

    I want to create classes for each of these functions and store them in a separate module. In my test run for the add password feature class, window creation and adding labels and buttons are working fine but the logo image is not being displayed, even though the canvas is being created.

    Google and Stack Overflow tells me that this issue is caused by python's garbage collection mechanism but in spite of having created a persistent reference to the image, the image is still not being displayed. I simply cannot figure out where I'm making a mistake.

    This is an extract of my attempt to create an "Add Password Window" class:

    from tkinter import *
    from PIL import ImageTk, Image

    class AddPasswordWindow:
    def __init__(self, master_window):
    self.master_window = master_window
    self.add_window = Toplevel(self.master_window)
    self.logo = ImageTk.PhotoImage(Image.open("password_img.png"))
    self.create_add_window()
    self.create_canvas()

    def create_add_window(self):
    self.add_window.title("Add a password")
    self.add_window.config(padx=50, pady=50)

    def create_canvas(self):
    canvas = Canvas(self.add_window, width=205, height=205)
    canvas.create_image(102, 102, image=self.logo)
    canvas.grid(column=0, row=0)


    This is an extract of my corresponding main.py:

    from tkinter import *
    import child_windows

    # Launch this function when the Add button is clicked
    def launch_add_password_window():
    child_windows.AddPasswordWindow(main_window)

    # User Interface
    # Create root window
    main_window = Tk()
    main_window.title("Password Manager")
    main_window.config(padx=15, pady=15)

    # Create Add Button
    add_button = Button(main_window, command=launch_add_password_window, text="Add Password")
    add_button.grid(column=0, row=0)

    main_window.mainloop()

    Continue reading...

Compartilhe esta Página