-3

I have a tkinter python file saved in a folder on the directory. The icons and other resources are for the file are saved in another folder.

root_directory
|
|---resources
|   |
|   |---icon.png
|
|---windows
|   |
|   |---tkinter_file.py

In tkinter_file.py, I want to set an icon for the tkinter window. So, I did something like: root.iconphoto(False, tk.PhotoImage(file='../resources/icon.png'))

But, this shows up an error: _tkinter.TclError: couldn't open "../resources/icon-appointment.png": no such file or directory

Please help me out to successfully locate the PNG file located in a different folder.

2 Answers2

2

You can get the relative path to icon.png from __file__, which is the path to your current source file:

import os
thisdir = os.path.dirname(__file__)
rcfile = os.path.join(thisdir, '..', 'resources', 'icon.png')

then

...  root.iconphoto(False, tk.PhotoImage(file=rcfile))
AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
  • Thanks! That error has been removed now. But, a new error has occurred now. It says: `_tkinter.TclError: can't use "pyimage8" as iconphoto: not a photo image` @AbbeGijly – Naman Chauhan Apr 28 '20 at 17:15
1

If you use relative path, you're at the mercy of your current working directory, which may not always be (...)/root/windows. Most likely your current directory is wherever you are executing your Python executable/shell. You'll want to use absolute path or update your current directory:

import os
os.chdir('(...)/root_directory') # fill in your absolute path to root_directory

An inelegant method would be to change the directory to wherever your current .py file is and then work your way back:

cur_dir = os.path.dirname(__file__)
os.chdir(os.path.join(cur_dir, '../resources/icon-appointment.png')

The more proper way would be to run your script as a module so it retains project structure.

r.ook
  • 13,466
  • 2
  • 22
  • 39