pyqt5如何使用QLabel显示多张图片
时间: 2023-07-16 15:16:40 浏览: 51
你可以使用QStackedWidget和QLabel来显示多张图片。首先,你需要创建一个QStackedWidget来存储所有的QLabel,每个QLabel都用于显示一张图片。然后,你可以使用QPixmap加载图片并将其设置为QLabel的背景。最后,通过QStackedWidget的setCurrentIndex方法切换要显示的QLabel。
以下是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QStackedWidget
from PyQt5.QtGui import QPixmap
class ImageWidget(QWidget):
def __init__(self, image_path):
super().__init__()
pixmap = QPixmap(image_path)
label = QLabel(self)
label.setPixmap(pixmap)
layout = QVBoxLayout(self)
layout.addWidget(label)
self.setLayout(layout)
class MultiImageWidget(QWidget):
def __init__(self, image_paths):
super().__init__()
stacked_widget = QStackedWidget(self)
for image_path in image_paths:
image_widget = ImageWidget(image_path)
stacked_widget.addWidget(image_widget)
layout = QVBoxLayout(self)
layout.addWidget(stacked_widget)
self.setLayout(layout)
self.current_index = 0
self.stacked_widget = stacked_widget
def next_image(self):
self.current_index += 1
if self.current_index >= self.stacked_widget.count():
self.current_index = 0
self.stacked_widget.setCurrentIndex(self.current_index)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
widget = MultiImageWidget(['image1.jpg', 'image2.jpg', 'image3.jpg'])
widget.show()
sys.exit(app.exec_())
```
这个示例程序中,MultiImageWidget继承自QWidget并显示了三张图片。你可以通过next_image方法切换要显示的图片。