Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind relative image path to *.py file

Tags:

python

qt

pyqt

I'm trying to create PyQt-application that contains directory with images. Problem is that if I'm trying to load image using it's relative path it's result will depends on current directory from which application will be started.

E.g I've project with the following structure:

qttest/
├── gui.py
└── icon.png

gui.py source:

import sys

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)

main = QMainWindow()
lbl = QLabel()
lbl.setPixmap(QPixmap("icon.png"))
main.setCentralWidget(lbl)
main.show()

sys.exit(app.exec_())

Now if I'll try to launch it from project directory with python3 gui.py it will succesfully load image and display it but if I'll launch it from parent directory with python3 qttest/gui.py it won't work.

Is there are any way to bind image to source file where it's used without hardcoding full image path?

like image 460
anlar Avatar asked Apr 07 '26 21:04

anlar


1 Answers

import os

path = os.path.dirname(os.path.abspath(__file__))
lbl.setPixmap(QPixmap(os.path.join(path, 'icon.png')))
like image 107
anlar Avatar answered Apr 10 '26 10:04

anlar