Python 如何使用 PyQt5 设置窗口图标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42602713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a window icon with PyQt5?
提问by HumanAfterAll
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?
我究竟做错了什么?
回答by DomTomCat
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'))
回答by drgrujic
The command, as suggested by asker, works for me:
按照提问者的建议,该命令对我有用:
self.setWindowIcon(QtGui.QIcon('icon.png'))
I put 256x256 png and all was OK. I have Win 7 pro 64 bit, Python 3.5.2 32 bit.
我放了 256x256 png,一切正常。我有 Win 7 pro 64 位,Python 3.5.2 32 位。
回答by Santanu Pal
I'm using PyQT5. And code should be as...
我正在使用 PyQT5。代码应该是...
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("programmer.png"), QtGui.QIcon.Selected, QtGui.QIcon.On)
MainWindow.setWindowIcon(icon)
回答by Yassin Mohammed
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'))