-2
#imports
from tkinter import *
import os
#Window Creation
window = Tk()
window.title('Potato Defense')
window.configure(width=1500, height=1500)
window.configure(bg='lightblue')
photo = PhotoImage(file = r"TestButton.png")
Button(window, text = 'Click Me !', image = photo).pack(side = TOP)

window.mainloop()

my code is quite janky, but currently, my image location gives an error because I don't know how to get the current location of files I don't want my directory I want it to work on other pcs. how do I get a current directory?

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

  • You have to KNOW where the files will be. Are you bundling this into an executable? Are you including the images when you build the exe? And note that "current directory" is almost never what you want in this case. You don't know what the "current directory" is when others run the app. You usually want the directory where the Python script is located, because the exe builders put the data files there. You can get that from `os.dirname(__file__)`. – Tim Roberts Nov 29 '22 at 05:50
  • no, I will prob be posting it to GitHub as a .zip, but I'm unsure as of now – BryanThePotato Nov 29 '22 at 05:53
  • do i set `os.dirname(__file__)` as a variable? – BryanThePotato Nov 29 '22 at 05:55
  • this also does not work as a variable as I do not need the file that the .py is I need the directory of the .py, not the .py itself – BryanThePotato Nov 29 '22 at 06:01
  • AttributeError: module 'os' has no attribute 'dirname' – BryanThePotato Nov 29 '22 at 06:04
  • Sorry, `os.path.dirname`. – Tim Roberts Nov 29 '22 at 07:32

1 Answers1

-2

If your code is in the same directory as this file, you can simply do photo = PhotoImage(file = "./TestButton.png")

Deep Shah
  • 44
  • 8
  • when I do this I get this error `_tkinter.TclError: couldn't open "./TestButton.png": no such file or directory` – BryanThePotato Nov 29 '22 at 05:58
  • Then that means the file is NOT in the "current directory" when you run. – Tim Roberts Nov 29 '22 at 07:32
  • Please provide more context about where the picture is in relation to your python script then. – Deep Shah Nov 29 '22 at 15:05
  • This answer isn't correct. Relative paths are relative to the current working directory, and that may or may not be the same folder as the file. – Bryan Oakley Nov 29 '22 at 19:07
  • but it is in the same directory – BryanThePotato Nov 29 '22 at 19:58
  • Starting Potato Defense Traceback (most recent call last): File "/home/btp/.coding/Potato Defense FIles/Potato_defense.py", line 13, in photo = PhotoImage(file = r"./TestButton.png") File "/usr/lib/python3.9/tkinter/__init__.py", line 4064, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/usr/lib/python3.9/tkinter/__init__.py", line 4009, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "./TestButton.png": no such file or directory – BryanThePotato Nov 29 '22 at 20:00