1

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
4

1 回答 1

0

sys.path包含 python 导入模块的路径列表,这不适用于导入文件、图标或类似资源。相反,最好创建一个函数,将目录路径与文件名绑定并返回图标的完整路径:

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_())
于 2019-02-19T04:46:02.923 回答