【发布时间】:2018-10-23 02:46:39
【问题描述】:
我编写了以下代码来使用 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())
【问题讨论】:
标签: python pyqt pyqt5 qmainwindow qlabel