Search code examples
pythontkinter

_tkinter.TclError: can't use "pyimage1" as iconphoto: not a photo image


When I tried to add the file dialog button, I kept getting a error like this:

_tkinter.TclError: can't use "pyimage1" as iconphoto: not a photo image

This is my code:

from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from file_dialog import filedialog

root = Tk()
img = PhotoImage(file='icon.png')

root.geometry("700x500") # the application window size
root.iconphoto(False, img) # application icon
root.title("I need a NAME!") # title of window

def file_dialog():
    root.filename = filedialog.askopenfilename(initialdir="Downloads", title="Select A File To Start", filetypes=(("mp4 files", "*.mp4"),("mov files", "*.mov"),("png files", "*.png"),("jpeg files", "*.jpeg"),("jpg files", "*.jpg")))


def file_dialog_button(app):
    app = app.tk()
    button = app.Button(app, text="Start!", command=file_dialog)
    button.pack(app)

root.mainloop()

print("Succesful Build")

file_dialog()
file_dialog_button()

Solution

  • I've made a few modifications to your code that enables you to load images into the root window icon.

    from tkinter import * is a bad practice so I've changed it to import tkinter as tk and made the necessary changes.

    The problem was that you were attempting to reference functions and variables before they were declared.

    import tkinter as tk
    from PIL import ImageTk, Image
    from tkinter import filedialog
    
    root = tk.Tk()
    root.geometry("700x500") # the application window size
    root.title("I need a NAME!") # title of window
    
    def file_dialog():
        filename = filedialog.askopenfilename(
            initialdir="Downloads",
            title="Select A File To Start",
            filetypes=(
                ("mp4 files", "*.mp4"),
                ("mov files", "*.mov"),
                ("png files", "*.png"),
                ("jpeg files", "*.jpeg"),
                ("jpg files", "*.jpg")))
    
        if filename:
            root.img = tk.PhotoImage(file=filename)
            root.iconphoto( False, root.img ) # application icon
    
    app = tk.Toplevel(root)
    app.transient( root )
    button = tk.Button(app, text="Start!", command=file_dialog)
    button.pack(fill = "both", expand = True)
    
    root.mainloop()
    
    print("Successful Build")