skip to Main Content

I am attepmting to add an icon to my TK window but i keep getting an error message that says:

Traceback (most recent call last):
  File "C:UsersrogersourcereposPythonApplicationPythonApplication.py", line 7, in <module>
    windowIcon = tk.PhotoImage(file="C:/Users/roger/Downloads/a.png");
  File "C:UsersrogerAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 4064, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:UsersrogerAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 4009, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:/Users/roger/Downloads/a.png"

I have no clue what to do here. This is the code I am running, made in Microsoft visual studio

import tkinter as tk
print("Hi");
window = tk.Tk();
window.title("New Game!");
window.geometry("900x900");
from os import system
windowIcon = tk.PhotoImage(file="C:/Users/roger/Downloads/a.png");
window.iconphoto(windowIcon);
window.mainloop();

I was trying to add an icon, and expected the icon to appear on the window as it should have, instead I got the error message. Please help.

3

Answers


  1. Are you sure the file "a.png" exists in the location?

    Login or Signup to reply.
  2. I’m not so sure about your problem, because the error message is a bit complicated. What I do know is that .iconphoto() is very rarely seen in Python GUI codes using tkinter. Although I can’t fix your problem using .iconphoto(), I can provide a way to show the image using tk.Canvas(). The code is as follows:

    import tkinter as tk
    
    window = tk.Tk()
    window.title("New Game!")
    window.geometry("900x900")
    
    windowIcon = tk.PhotoImage(file='my_image.png')
    canvas = tk.Canvas(window, width=500, height=450, bg='white')
    canvas.pack()
    canvas.create_image(0, 0, anchor=tk.NW, image=windowIcon)
    window.mainloop()
    

    In the above code, I’m using the tk.Canvas() widget and the .create_image() of the canvas class to show the image. Also, you can check out the PIL library. As an example, the following code works just like the code above, but with added resizing functionality thanks to the PIL library:

    import tkinter as tk
    from PIL import ImageTk, Image
    
    window = tk.Tk()
    window.title("New Game!")
    window.geometry("900x900")
    
    img = Image.open('c01.png')
    img = img.resize((500, 450)) # to match the size of the canvas; you can change this to any size you want
    windowIcon = ImageTk.PhotoImage(img)
    
    canvas = tk.Canvas(window, width=500, height=450, bg='white')
    canvas.pack()
    canvas.create_image(0, 0, anchor=tk.NW, image=windowIcon)
    window.mainloop()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search