如何基于pycharm写出一个界面同时显示两个文件夹的图片
时间: 2024-05-01 14:17:13 浏览: 40
python pyecharts 实现一个文件绘制多张图
下面是一个基于PyQt5的示例代码,可以同时显示两个文件夹中的图片:
```python
import os
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Image Viewer")
self.left_folder = QtWidgets.QTreeView()
self.left_folder.setRootIsDecorated(False)
self.left_folder.setSortingEnabled(True)
self.left_folder.setModel(QtGui.QFileSystemModel())
self.left_folder.selectionModel().selectionChanged.connect(self.left_folder_selection_changed)
self.left_image = QtWidgets.QLabel()
self.left_image.setAlignment(QtCore.Qt.AlignCenter)
self.right_folder = QtWidgets.QTreeView()
self.right_folder.setRootIsDecorated(False)
self.right_folder.setSortingEnabled(True)
self.right_folder.setModel(QtGui.QFileSystemModel())
self.right_folder.selectionModel().selectionChanged.connect(self.right_folder_selection_changed)
self.right_image = QtWidgets.QLabel()
self.right_image.setAlignment(QtCore.Qt.AlignCenter)
main_widget = QtWidgets.QWidget()
main_layout = QtWidgets.QHBoxLayout()
main_layout.addWidget(self.left_folder)
main_layout.addWidget(self.left_image)
main_layout.addWidget(self.right_folder)
main_layout.addWidget(self.right_image)
main_widget.setLayout(main_layout)
self.setCentralWidget(main_widget)
def left_folder_selection_changed(self, selected, deselected):
index = selected.indexes()[0]
file_model = QtGui.QFileSystemModel()
file_model.setRootPath(index.data())
file_model.setNameFilters(["*.jpg", "*.png"])
file_model.setNameFilterDisables(False)
self.left_image.setPixmap(QtGui.QPixmap(file_model.filePath(index)))
def right_folder_selection_changed(self, selected, deselected):
index = selected.indexes()[0]
file_model = QtGui.QFileSystemModel()
file_model.setRootPath(index.data())
file_model.setNameFilters(["*.jpg", "*.png"])
file_model.setNameFilterDisables(False)
self.right_image.setPixmap(QtGui.QPixmap(file_model.filePath(index)))
if __name__ == '__main__':
app = QtWidgets.QApplication([])
win = MainWindow()
win.show()
app.exec_()
```
这个界面中有两个QTreeView控件,分别显示两个文件夹的目录结构,当选择某个文件时,会在相应的QLabel控件中显示该文件的图片。可以通过在left_folder_selection_changed()和right_folder_selection_changed()方法中设置过滤条件来控制只显示jpg和png格式的图片。
阅读全文