在PyQt5中使用菜单栏打开并保存图像文件

时间:2018-05-13 06:34:19

标签: python pyqt pyqt5 qmainwindow qlabel

我已经使用PyQt5中的菜单栏编写了以下代码来打开图像文件。它能够选择文件,但无法在窗口中显示。我已成功打开文本文件但无法对图像执行相同操作。你能纠正我的错误吗?

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QLabel, QFileDialog, QAction
from PyQt5.QtGui import QIcon, QPixmap

class MainWindow(QMainWindow):

    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        editMenu = menubar.addMenu('Edit')
        self.resize(500, 500)

        dlg = QFileDialog(self)       
        openAction = QAction('Open Image', self)  
        openAction.triggered.connect(self.openImage) 
        fileMenu.addAction(openAction)

        closeAction = QAction('Exit', self)  
        closeAction.triggered.connect(self.close) 
        fileMenu.addAction(closeAction)



    def openImage(self):
    # This function is called when the user clicks File->Open Image.
        label = QLabel(self)
        filename = QFileDialog.getOpenFileName()
        imagePath = filename[0]
        print(imagePath)
        pixmap = QPixmap(imagePath)
        label.setPixmap(pixmap)
        self.resize(pixmap.width(),pixmap.height())
        self.show()



def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()

if __name__ == '__main__':
    sys.exit(main()) 

1 个答案:

答案 0 :(得分:1)

当您调用show()时,窗口小部件会显示子项,在您使用该方法时,QLabel不是子项,因此一个简单但部分的解决方案是使其可见:

def openImage(self):
    label = QLabel(self)
    label.show()
    # or
    # self.show()

但是在QMainWindow不合适的情况下,QMainWindow是一个非常特殊的小部件,因为它具有明确的结构,如下图所示:

enter image description here

正如您所看到的,QLabel是centralWidget并且只创建一次,然后您只需要在选择新图像时替换QPixmap:

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog, QAction
from PyQt5.QtGui import QPixmap

class MainWindow(QMainWindow):

    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        editMenu = menubar.addMenu('Edit')
        self.resize(500, 500)

        openAction = QAction('Open Image', self)  
        openAction.triggered.connect(self.openImage) 
        fileMenu.addAction(openAction)

        closeAction = QAction('Exit', self)  
        closeAction.triggered.connect(self.close) 
        fileMenu.addAction(closeAction)
        self.label = QLabel()
        self.setCentralWidget(self.label)

    def openImage(self):
        imagePath, _ = QFileDialog.getOpenFileName()
        pixmap = QPixmap(imagePath)
        self.label.setPixmap(pixmap)
        self.resize(pixmap.size())
        self.adjustSize()

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    return app.exec_()

if __name__ == '__main__':
    sys.exit(main())