简体   繁体   English

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

[英]How to set a window icon with PyQt5?

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'))

I am trying to set a window icon (top left of the window) but the normal icon disappeared instead.我正在尝试设置一个窗口图标(窗口的左上角),但普通图标却消失了。

I tried with many icon resolutions (8x8, 16x16, 32x32, 64x64) and extensions (.png and .ico).我尝试了许多图标分辨率(8x8、16x16、32x32、64x64)和扩展名(.png 和 .ico)。

What am I doing wrong?我究竟做错了什么?

The command, as suggested by asker, works for me:按照提问者的建议,该命令对我有用:

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

I put 256x256 png and all was OK.我放了 256x256 png,一切正常。 I have Win 7 pro 64 bit, Python 3.5.2 32 bit.我有 Win 7 pro 64 位,Python 3.5.2 32 位。

The answer has been given by the asker (invisible icon).答案已由提问者给出(隐形图标)。 I wanted to add that the script may not be executed in the script directory.我想补充一点,脚本可能不会在脚本目录中执行。 In any case, to be safe, you may want to make sure the icon is loaded relative to the directory in which the script resides:在任何情况下,为了安全起见,您可能需要确保图标是相对于脚本所在的目录加载的:

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

I'm using PyQT5.我正在使用 PyQT5。 And code should be as...代码应该是...

icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("programmer.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
MainWindow.setWindowIcon(icon)
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'))        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM