Search code examples
pythontkintericons

.ico file not defined in Python Tkinter


So I was making a tkinter app project but then I came across this error.

Traceback (most recent call last):
  File "c:\storage\program\py\binary drawer\main.py", line 166, in <module>
    root.iconbitmap("pencil.ico")
  File "C:\Users\bhone\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2136, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: bitmap "pencil.ico" not defined

The file "pencil.ico" was in C:\storage\program\py\binary drawer. The name was right and the path was right. How can I fix this error?

I'm using python 3.11.3. I'm using Windows 11.


Solution

  • The error means that the ICON file cannot be found in current working directory which may not be the same directory where the script is.

    If you want to load the ICON file in the same directory of the script, you can build the full path of the ICON file using internal variable __file__ as below:

    from pathlib import Path
    
    ...
    
    appdir = Path(__file__).parent    # get the directory where the script is
    iconfile = appdir / "pencil.ico"  # build the full path of the ICON file
    root.iconbitmap(iconfile)