Home > Back-end >  How do I use a relative path to access a png file
How do I use a relative path to access a png file

Time:03-12

So I am running this code:

from tkinter import *

# Variables
HomeGUI = Tk()
CamBut = Button(HomeGUI)
CamLogo = PhotoImage(file=r"C:\Users\adity\PycharmProjects\Front End for MediScan\CamLogo.PNG")


# Function opens GUI for home screen
def runhome():
    # Setting global variables
    global CamBut
    global HomeGUI

    CamBut.config(image=CamLogo)
    CamBut.pack()
    HomeGUI.mainloop()


runhome()

And I want to be able to access CamLogo.PNG using a relative path, as the direct path will not work on another device, how could I do this? CamLogo.png is in the same folder as the code above.

CodePudding user response:

If its in the same folder then you'd simply do:

CamLogo = PhotoImage(file="CamLogo.PNG")

CodePudding user response:

A . refers to the current directory.
If we are in "C:\Users\adity\PycharmProjects\Front End for MediScan" then you can use the relative path ".\CamLogo.png".

NB: It is a good idea to avoid spaces in directory file names. Either use camelCase as you have done in "PycharmProjects" or underscores: "Front_End_for_MediScan" This will avoid the obligation to use, and escape, speech marks and reduce the risk of error messages such as "file not found".

  • Related