顯示介面
pyqt_code.py
===================================================
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QFileDialog, QGridLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
class ImageDisplayApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# 創建按鈕
self.button1 = QPushButton('選擇 BMP 圖片', self)
self.button1.setFixedSize(100, 40)
self.button1.clicked.connect(self.open_file_dialog)
self.button2 = QPushButton('選擇 BMP 圖片 2', self)
self.button2.setFixedSize(100, 40)
self.button2.clicked.connect(self.open_file_dialog_2)
self.button3 = QPushButton('按鈕 3', self)
self.button3.setFixedSize(100, 40)
self.button4 = QPushButton('按鈕 4', self)
self.button4.setFixedSize(100, 40)
self.button5 = QPushButton('按鈕 5', self)
self.button5.setFixedSize(100, 40)
self.button6 = QPushButton('按鈕 6', self)
self.button6.setFixedSize(100, 40)
# 創建顯示圖形的標籤
self.image_label = QLabel('尚未選擇圖片', self)
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setScaledContents(False)
self.image_label_2 = QLabel('尚未選擇圖片 2', self)
self.image_label_2.setAlignment(Qt.AlignCenter)
self.image_label_2.setScaledContents(False)
# 創建顯示檔案路徑的標籤
self.lab1 = QLabel('尚未選擇檔案路徑', self)
self.lab1.setAlignment(Qt.AlignLeft)
# 設置按鈕佈局
button_layout = QVBoxLayout()
button_layout.addWidget(self.button1)
button_layout.addWidget(self.button2)
button_layout.addWidget(self.button3)
button_layout.addWidget(self.button4)
button_layout.addWidget(self.button5)
button_layout.addWidget(self.button6)
button_layout.addStretch()
# 設置圖片佈局,兩個圖像標籤垂直顯示且不重疊
image_layout = QVBoxLayout()
image_layout.addWidget(self.lab1)
image_layout.addWidget(self.image_label)
image_layout.addWidget(self.image_label_2)
image_layout.addStretch()
# 設置主佈局
main_layout = QHBoxLayout()
main_layout.addLayout(button_layout)
main_layout.addLayout(image_layout)
self.setLayout(main_layout)
# 設置窗口屬性
self.setWindowTitle('PyQt5 圖片顯示範例')
self.setGeometry(100, 100, 1000, 600)
self.show()
def open_file_dialog(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, '選擇 BMP 圖片', '', 'BMP Files (*.bmp);;All Files (*)', options=options)
if file_name:
pixmap = QPixmap(file_name)
self.image_label.setPixmap(pixmap)
self.image_label.setFixedSize(pixmap.size())
self.lab1.setText(f'選擇的檔案路徑: {file_name}')
def open_file_dialog_2(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, '選擇 BMP 圖片 2', '', 'BMP Files (*.bmp);;All Files (*)', options=options)
if file_name:
pixmap = QPixmap(file_name)
self.image_label_2.setPixmap(pixmap)
self.image_label_2.setFixedSize(pixmap.size())
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ImageDisplayApp()
sys.exit(app.exec_())