【问题标题】:Beginner on PyQt4 - No window iconPyQt4 初学者 - 没有窗口图标
【发布时间】:2014-02-15 11:13:30
【问题描述】:

我不明白为什么我的窗口上绝对没有显示图标。该图标与 python 脚本位于同一目录中。

import sys
from PyQt4 import QtGui

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon_test')
        self.setWindowIcon(QtGui.QIcon('application-icon.png'))        

        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()    

非常感谢任何帮助!

【问题讨论】:

  • 相对路径才能起作用,它必须是相对于当前目录的,它不一定与python脚本所在的目录相同。

标签: python python-2.7 icons pyqt pyqt4


【解决方案1】:

您需要指定图像文件的完整路径。

import sys
import os.path as osp
from PyQt4 import QtGui

#setting the path variable for icon
path = osp.join(osp.dirname(sys.modules[__name__].__file__), 'application-icon.png')

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon_test')
        self.setWindowIcon(QtGui.QIcon(path))        

        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

sys.modules[__name__].__file__ 会给出当前模块路径

【讨论】:

  • 您可以将sys.modules[__name__].__file__ 缩短为__file__(是的,它是在代码实际执行之前为所有模块定义的全局变量)。
  • “完整路径”也可能与应用程序的运行位置相关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
相关资源
最近更新 更多