帮我写一个用pyqt打开图片的代码,并且可以调整大小
时间: 2023-05-17 07:04:30 浏览: 226
打开图片的代码
当然可以,以下是一个简单的用 PyQt 打开图片并调整大小的代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap
class ImageWidget(QWidget):
def __init__(self, image_path):
super().__init__()
self.image_path = image_path
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 400, 400)
self.setWindowTitle('Image Viewer')
# Load the image
pixmap = QPixmap(self.image_path)
# Create a label to display the image
label = QLabel(self)
label.setPixmap(pixmap)
label.setAlignment(Qt.AlignCenter)
# Create a layout and add the label to it
layout = QVBoxLayout()
layout.addWidget(label)
# Set the layout for the widget
self.setLayout(layout)
def resizeEvent(self, event):
# Resize the image when the widget is resized
pixmap = QPixmap(self.image_path)
pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio)
self.label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
image_widget = ImageWidget('image.jpg')
image_widget.show()
sys.exit(app.exec_())
```
这个代码会打开一个名为 "image.jpg" 的图片,并且可以调整大小。你可以将 "image.jpg" 替换成你想要打开的图片的路径。
阅读全文