QPushButton指定图片
时间: 2024-05-01 14:22:58 浏览: 37
可以使用QPushButton的`setIcon()`方法来指定图片。示例代码如下:
```python
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
app = QApplication([])
window = QWidget()
button = QPushButton('Click me!', window)
icon = QIcon('path/to/image.png')
button.setIcon(icon)
window.show()
app.exec_()
```
在上面的代码中,我们创建了一个QPushButton,然后使用setIcon()方法来指定图标。我们首先创建了一个QIcon对象,并将其传递给setIcon()方法。在这里,我们将图标文件的路径作为参数传递给QIcon构造函数。
如果您希望在按钮上同时显示文本和图标,可以使用`setToolButtonStyle()`方法来指定按钮的样式。示例代码如下:
```python
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
app = QApplication([])
window = QWidget()
button = QPushButton('Click me!', window)
icon = QIcon('path/to/image.png')
button.setIcon(icon)
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
window.show()
app.exec_()
```
在这个例子中,我们使用了`setToolButtonStyle()`方法来指定按钮的样式为`Qt.ToolButtonTextBesideIcon`,这将使按钮同时显示文本和图标。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)