pythonpyqtpyqt5python-3.7qicon

Why python not show in path icon?


I wrote below code

import sys,time
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)
sys.path.append(r"C:\Users\hpaalm\Desktop")
a=QPushButton()
a.setIcon(QIcon('1.png'))
a.show()
app.exec_()

when i run it in IDE, it show my icon, but when run it in CMD it not show icon. what is problem?

python C:\Users\hpaalm\Desktop\a.py

Solution

  • sys.path contains a list of paths where python imports the modules, this does not serve to import files, icons or similar resources. Instead it is best to create a function that binds the directory path with the filename and return the full path of the icon:

    import os
    import sys
    from PyQt5 import QtGui, QtWidgets
    
    ICON_DIR = r"C:\Users\hpaalm\Desktop"
    
    def get_path_icon(filename):
        return os.path.join(ICON_DIR, filename)
    
    if __name__ == '__main__':
    
        app = QtWidgets.QApplication(sys.argv)
    
        a = QtWidgets.QPushButton()
        a.setIcon(QtGui.QIcon(get_path_icon('1.png')))
        a.show()
        sys.exit(app.exec_())