Why isn't .ico file defined when setting window's icon?

CrushedPixel picture CrushedPixel · Aug 30, 2013 · Viewed 126k times · Source

When I tried to change the window icon in the top left corner from the ugly red "TK" to my own favicon using the code below, Python threw an error:

from tkinter import *
root = Tk()

#some buttons, widgets, a lot of stuff

root.iconbitmap('favicon.ico')

This should set the icon to 'favicon.ico' (according to a lot of forum posts all over the web). But unfortunately, all this line does is throw the following error:

Traceback (most recent call last):
  File "d:\ladvclient\mainapp.py", line 85, in <module>
    root.iconbitmap(bitmap='favicon.ico')
  File "C:\Python33\lib\tkinter\__init__.py", line 1637, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "favicon.ico" not defined

What I already did:

  • I checked the path - everything is 100% correct
  • I tried other file formats like .png or .bmp - none worked
  • I looked this problem up on many websites

And for the third point, effbot.org, my favorite site about Tkinter, told me that Windows ignores the iconbitmap function. But this doesn't explain why it throws an error!

There are some "hackish" ways to avoid that issue, but none of them are Written for Python 3.x.

So my final question is: Is there a way to get a custom icon using Python 3.x and Tkinter?

Also, don't tell me I should use another GUI Library. I want my program to work on every platform. I also want a coded version, not a py2exe or sth solution.

Answer

user2555451 picture user2555451 · Aug 30, 2013

You need to have favicon.ico in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:

from tkinter import *
root = Tk()

root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()

But this blows up with your same error:

from tkinter import *
root = Tk()

root.iconbitmap('py.ico')
root.mainloop()