pyqt给按钮一个img
时间: 2023-11-02 10:12:29 浏览: 30
给按钮添加图像的方法:
1. 创建一个QPixmap对象:`pixmap = QPixmap("image.png")`
2. 获取按钮的大小:`button_size = button.size()`
3. 调整图片大小以适应按钮:`pixmap = pixmap.scaled(button_size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)`
4. 设置按钮的图像:`button.setIcon(QIcon(pixmap))`
完整的示例代码:
```python
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
window.setLayout(layout)
button = QPushButton()
pixmap = QPixmap("image.png")
button_size = button.size()
pixmap = pixmap.scaled(button_size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation)
button.setIcon(QIcon(pixmap))
layout.addWidget(button)
window.show()
app.exec_()
```