PyQt5 – 在按钮上添加图像图标

PyQt5 – 在按钮上添加图像图标

在这篇文章中,我们将看到如何为一个按钮添加图标。在这里,设置图标不像设置背景图片,它类似于主窗口的图标。按钮的图标出现在左边,文字在右边。下面是没有图标和有图标的按钮的表示方法。

PyQt5 - 在按钮上添加图像图标 PyQt5 - 在按钮上添加图像图标

为了实现这个目的,我们将使用setIcon方法。

语法: button.setIcon(QIcon(‘logo.png’))

参数: 如果在同一个文件夹中,它需要文件名,否则需要文件路径

执行的动作: 它为按钮设置图标。

代码。

# importing libraries
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
 
 
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
 
        # setting title
        self.setWindowTitle("Python ")
 
        # setting geometry
        self.setGeometry(100, 100, 600, 400)
 
        # calling method
        self.UiComponents()
 
        # showing all the widgets
        self.show()
 
    # method for widgets
    def UiComponents(self):
 
        # creating a push button
        button = QPushButton("CLICK", self)
 
        # setting geometry of button
        button.setGeometry(200, 150, 100, 30)
 
        # adding action to a button
        button.clicked.connect(self.clickme)
 
        # setting icon to the button
        button.setIcon(QIcon('logo.png'))
 
 
 
    # action method
    def clickme(self):
 
        # printing pressed
        print("pressed")
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# start the app
sys.exit(App.exec())

输出 :

PyQt5 - 在按钮上添加图像图标

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程