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
Are you sure the file "a.png" exists in the location?
Check this question: https://stackoverflow.com/questions/47357090/tkinter-error-couldnt-recognize-data-in-image-file#:~:text=To%20answer%20the%20original%20question,the%20%22inter%22%20part).
It seems some versions of tk do not support png.
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 usingtkinter
. Although I can’t fix your problem using.iconphoto()
, I can provide a way to show the image usingtk.Canvas()
. The code is as follows: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 thePIL
library. As an example, the following code works just like the code above, but with added resizing functionality thanks to thePIL
library: