代码如下
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setWindowTitle("图片处理")
self.setGeometry(200, 200, 500, 400)
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
main_layout = QVBoxLayout() # 整体的垂直布局
# 上面两个 label 的水平布局
label_layout = QHBoxLayout()
self.label1 = QLabel()
label_layout.addWidget(self.label1) # 图片 1 居左
self.label2 = QLabel()
label_layout.addWidget(self.label2) # 图片 2 居右
main_layout.addLayout(label_layout) # 将水平布局添加到垂直布局
# 下面两个按钮的水平布局
button_layout = QHBoxLayout()
self.button1 = QPushButton("打开图片")
self.button1.clicked.connect(self.open_image)
button_layout.addWidget(self.button1)
self.button2 = QPushButton("复制图片")
self.button2.clicked.connect(self.copy_image)
button_layout.addWidget(self.button2)
main_layout.addLayout(button_layout) # 将水平布局添加到垂直布局
self.central_widget.setLayout(main_layout) # 设置中央部件的布局
def open_image(self):
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(self, "选择图片", "", "Image Files (*.jpg *.png)")
if file_path:
pixmap = QPixmap(file_path)
self.label1.setPixmap(pixmap)
def copy_image(self):
pixmap = self.label1.pixmap()
if pixmap:
self.label2.setPixmap(pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())