如何使用PyQt5设置窗口图标?

时间:2017-03-04 23:46:48

标签: python icons pyqt5 qmainwindow python-3.6

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Application(QMainWindow):
    def __init__(self):
        super(Application, self).__init__()
        self.setWindowIcon(QtGui.QIcon('icon.png'))

我正在尝试设置一个窗口图标(窗口的左上角),但正常的图标却消失了。

我尝试了许多图标分辨率(8x8,16x16,32x32,64x64)和扩展名(.png和.ico)。

我做错了什么?

4 个答案:

答案 0 :(得分:4)

答案是由提问者给出的(隐形图标)。我想补充一点,脚本可能不会在脚本目录中执行。在任何情况下,为了安全起见,您可能希望确保相对于脚本所在的目录加载图标:

import os 
# [...]
scriptDir = os.path.dirname(os.path.realpath(__file__))
self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep + 'logo.png'))

答案 1 :(得分:4)

这个命令,如提问者所建议,对我有用:

 self.setWindowIcon(QtGui.QIcon('icon.png'))

我把256x256 png,一切都还可以。我有Win 7 pro 64位,Python 3.5.2 32位。

答案 2 :(得分:1)

我正在使用PyQT5。并且代码应为...

icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("programmer.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
MainWindow.setWindowIcon(icon)

答案 3 :(得分:1)

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon


class Example(QWidget):

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

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png'))        
相关问题