import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyPDF2 import PdfFileReader, PdfFileWriter
from main_form import * class MyWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
self.actionLoad_File_L.triggered.connect(self.showDialog) def showDialog(self):
infn = QFileDialog.getOpenFileName(self,
'Open file',
'd:') with open(infn, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages() print(info, number_of_pages) if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())

原因是getOpenFileName的返回值是文件名文件类型的元组,这里直接把元组赋值给了open函数,但是应该是文件名,自己对于代码基础原理不够理解,实际实例代码都有写

infn = QFileDialog.getOpenFileName(self,
'Open file',
'd:')[0]

我没有仔细观察,花了1个小时解决这个问题

pycharm没有报这个错误,到命令行运行可以很清晰的看到这个错误,pycharm假死,所以pycharm也不可靠啊

pyqt5加载pdf文档失败-LMLPHP

所以可以像下面这样写

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyPDF2 import PdfFileReader, PdfFileWriter
from main_form import * class MyWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
self.actionLoad_File_L.triggered.connect(self.get_info) def get_info(self):
path = 'D:/coding/envs/brisspython/a.pdf'
filename, filetype = QFileDialog.getOpenFileName(self, 'Open file')
with open(filename, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages() print(number_of_pages) if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())

或者

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyPDF2 import PdfFileReader, PdfFileWriter
from main_form import * class MyWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setupUi(self)
self.actionLoad_File_L.triggered.connect(self.get_info) def get_info(self):
path = 'D:/coding/envs/brisspython/a.pdf'
filename = QFileDialog.getOpenFileName(self, 'Open file')[0]
with open(filename, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages() print(number_of_pages) if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
05-11 19:35
查看更多