Search code examples
pythontkinterrelative-pathabsolute-path

how to use another directory in the same folder without using absolute path - Tkinter


I made a python program using a library called tkinter. I would like to make this program work on Windows but I'm having paths problems. I made a folder called gui that stores images (like icons and buttons), however I can't use images from this folder without putting the entire path

from tkinter import *

janela = Tk()
janela.title("lofi-station")
janela.resizable(0,0)
janela.geometry("500x500")
janela.configure(bg='black')
background = PhotoImage(file='/home/myuser/projects/gui/backg1.gif')
janela.option_add('*tearOff',FALSE)
janela.mainloop()

I've tried using the relative path but it returns an error. Solving this problem is the key to getting this to work on windows

background = PhotoImage(file='./gui/backg1.gif')

the return:

Traceback (most recent call last):
  File "/home/myuser/projects/lofi_station.py", line 13, in <module>
    background = PhotoImage(file='./gui/backg1.gif')
  File "/usr/lib/python3.10/tkinter/__init__.py", line 4093, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/usr/lib/python3.10/tkinter/__init__.py", line 4038, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "./gui/backg1.gif": no such file or directory

after getting this resolved, i want to port this to windows, what would I need to change specifically?


Solution

  • background = PhotoImage(file=r'./gui/backg1.gif')

    try using this, might help