Home > front end >  how to use another directory in the same folder without using absolute path - Tkinter
how to use another directory in the same folder without using absolute path - Tkinter

Time:09-11

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?

CodePudding user response:

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

try using this, might help

CodePudding user response:

I've encountered the same problem few months ago. If you are running this code from a python IDE, then you better check the current working directory using os.getcwd() importing the module os. The relative path always uses the current working directory. If your cwd is not the expected one then the problem might be that you are on a different folder in your IDE. Just try printing os.getcwd() in your code. From my perspective the working directory should be /home/myuser/projects. If it prints that you may wanna try this code here:

from tkinter import *
import os

janela = Tk()
janela.title("lofi-station")
janela.resizable(0,0)
janela.geometry("500x500")
janela.configure(bg='black')
path = f"{os.getcwd()}/gui/backg1.gif"
background = PhotoImage(file=path)
janela.option_add('*tearOff',FALSE)
janela.mainloop()

Maybe the folder where the python code is executing is not in the projects folder. Hopefully, this answer solves your problem.

After resolving this error, you just need to have the same file structure of your project as you had on whatever you had before.

  • Related