【发布时间】:2021-02-27 23:20:33
【问题描述】:
我正在开发一个 GUI,它有一个名为“打开目录”的 2 个按钮,使用户能够打开他/她选择的目录。请注意,此目录仅包含图像。选择目录后,list_of_images 中的第一张图片将显示在窗口中。
还有另一个按钮叫做“下一步”。如果用户按下此按钮,则来自list_of_images 的下一个图像将显示在窗口上。
我的文件夹中有 3 张图片,这意味着我的 list_of_images = ['a.jpg', 'b.jpg', 'c.jpg']
现在我面临的问题是,当我按下按钮 next 时,会显示下一个图像,但是当我再次按下它时,它应该显示第三个图像,但它没有。代码中可能存在什么问题?
我将提供重现问题的代码。但是您需要更改文件夹或在您的机器上创建一个名为 test_images 的文件夹。
# Import pyqt stuff
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QApplication
# Import DL stuff
import matplotlib.pyplot as plt
# Import the python script generated by the Qt-Designer
from gui_firstdraft import Ui_main_window
# Import miscellaneous
import sys
import os
class mainProgram(QtWidgets.QMainWindow, Ui_main_window):
def __init__(self, parent=None):
# Inherit from the aforementioned class and set up the gui
super(mainProgram, self).__init__(parent)
self.setupUi(self)
def all_callbacks(self):
# Open directory callback
self.openDirectory_button.clicked.connect(self.open_directory_callback)
# Next button callback
self.next_button.clicked.connect(self.next_button_callback)
def open_directory_callback(self):
# Paths
self._base_dir = os.getcwd()
self._images_dir = os.path.join(self._base_dir, 'test_images')
# Open a File Dialog and select the folder path
dialog = QFileDialog()
self._folder_path = dialog.getExistingDirectory(None, "Select Folder")
# Get the list of images in the folder and read using matplotlib and print its shape
self.list_of_images = os.listdir(self._folder_path)
self.list_of_images = sorted(self.list_of_images)
# Length of Images
print('Number of Images in the selected folder: {}'.format(len(self.list_of_images)))
input_img_raw_string = '{}\\{}'.format(self._images_dir, self.list_of_images[0])
# Show the first Image in the same window. (self.label comes from the Ui_main_window class)
self.label.setPixmap(QtGui.QPixmap(input_img_raw_string))
self.label.show()
def next_button_callback(self):
# Total Images in List
total_images = len(self.list_of_images)
if self.list_of_images:
try:
for img in self.list_of_images:
self.label.setPixmap(QtGui.QPixmap('{}\\{}'.format(self._images_dir, img)))
self.label.show()
except ValueError as e:
print('The selected folder does not contain any images')
def execute_pipeline():
# Make an object of the class and execute it
app = QApplication(sys.argv)
# Make an object and call the functions
annotationGui = mainProgram()
annotationGui.all_callbacks()
annotationGui.show()
# Exit the window
sys.exit(app.exec_())
if __name__ == "__main__":
execute_pipeline()
我怀疑它与 next_button_callback 有关,但我不确定问题出在哪里。
【问题讨论】:
-
看起来下一个函数每次都会显示列表中的最后一个图像,因为它循环遍历列表并在每次迭代时重新设置像素图。
-
如何更改循环?有什么想法吗?
-
你不应该使用循环。保留当前图像的索引并递增以访问下一个。
-
@alec,索引不需要循环吗?我不太明白你的意思。对不起!
标签: python user-interface pyqt pyqt5