PyQt5 - Open new image window for each button click
我一直在玩PyQt5,被卡在这里。在某个菜单中,对于每个按钮单击(以及给定的numpy图像数组),我试图打开一个新的图像窗口(将numpy数组转换为图像)。
因此,首先,我对一个图像进行了处理(使用此答案将numpy图像数组转换为QPixmap):
NewNumpyImageWindow.py类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import cv2 import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel from PyQt5.QtGui import QPixmap, QImage class NewImage(QWidget): def __init__(self, npImage): super().__init__() label = QLabel(self) pixmap = self.ConvertNumpyToQPixmap(npImage) label.setPixmap(pixmap) self.resize(pixmap.width(), pixmap.height()) self.show() @staticmethod def ConvertNumpyToQPixmap(np_img): height, width, channel = np_img.shape bytesPerLine = 3 * width return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()) if __name__ == '__main__': app = QApplication(sys.argv) currentNumpyImage = cv2.imread("capture.png") window = NewImage(currentNumpyImage) sys.exit(app.exec_()) |
它工作正常。图像显示为新窗口。
现在,我希望每次按主菜单中的按钮时图像以新窗口显示。
因此,我尝试为每次按下(在"新建"按钮上)创建上述类的实例,但它不起作用。似乎该窗口显示为新窗口,并在代码完成后立即关闭。
NewNumpyImageWindowMenu.py类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import cv2 import sys from PyQt5 import QtWidgets from NewNumpyImageWindow import NewImage class Menu(QtWidgets.QMainWindow): def __init__(self, numpyPic): super().__init__() newAct = QtWidgets.QAction('New', self) self.numpyPicture = numpyPic newAct.triggered.connect(self.newPicture) toolbar = self.addToolBar('Exit') toolbar.addAction(newAct) self.setGeometry(300, 300, 350, 250) self.show() def newPicture(self): NewImage(self.numpyPicture) #From the previous class if __name__ == '__main__': currentNumpyImage = cv2.imread("capture.png") app = QtWidgets.QApplication(sys.argv) ex = Menu(currentNumpyImage) sys.exit(app.exec_()) |
任何帮助将不胜感激。谢谢。
尝试:
NewNumpyImageWindowMenu.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import cv2 import sys from PyQt5 import QtWidgets from NewNumpyImageWindow import NewImage class Menu(QtWidgets.QMainWindow): def __init__(self, numpyPic): super().__init__() newAct = QtWidgets.QAction('New', self) self.numpyPicture = numpyPic newAct.triggered.connect(self.newPicture) toolbar = self.addToolBar('Exit') toolbar.addAction(newAct) self.setGeometry(300, 300, 350, 250) self.show() def newPicture(self): #NewImage(self.numpyPicture) #From the previous class # --- self.newImage = NewImage(self.numpyPicture) # +++ if __name__ == '__main__': #currentNumpyImage = cv2.imread("capture.png") currentNumpyImage = cv2.imread("logo.png") app = QtWidgets.QApplication(sys.argv) ex = Menu(currentNumpyImage) sys.exit(app.exec_()) |