Python 将图像放在 QPushButton 上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23634241/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:15:36  来源:igfitidea点击:

Put an Image on a QPushButton

pythonpyqt

提问by Margarita Gonzalez

I'm a beginner in PyQt and I have an image known as add.gif. I need to put this image in a QPushButtonbut I don't know how.

我是 PyQt 的初学者,我有一个名为add.gif. 我需要把这张图片放在 aQPushButton但我不知道怎么做。

回答by M4rtini

Assuming pyqt supports gif pictures, this should work

假设pyqt支持gif图片,这应该有效

icon  = QtGui.QPixmap('add.gif')
button = QtGui.QPushButton()
button.setIcon(icon)

QPushButton

Q按钮

Push buttons display a textual label, and optionally a small icon. These can be set using the constructors and changed later using setText() and setIcon(). If the button is disabled, the appearance of the text and icon will be manipulated with respect to the GUI style to make the button look "disabled".

按钮显示文本标签,以及可选的小图标。这些可以使用构造函数设置,稍后使用 setText() 和 setIcon() 更改。如果按钮被禁用,文本和图标的外观将根据 GUI 样式进行操作,使按钮看起来“禁用”。

回答by NorthCat

Example:

例子:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('', self)
        self.button.clicked.connect(self.handleButton)
        self.button.setIcon(QtGui.QIcon('myImage.jpg'))
        self.button.setIconSize(QtCore.QSize(24,24))
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        pass


if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())