一直使用Python很短的時間,並且無法弄清楚這段代碼有什麼問題。我找不到任何適用於我的代碼的例子,所以我在這裏問。如何在tkinter和PyPDF2中使用全局變量來合併PDF文件
import sys
import os
from PyPDF2 import PdfFileReader, PdfFileMerger, PdfFileWriter
from tkinter import *
gui = Tk()
gui.resizable(0,0)
gui.geometry("800x600")
gui.title("PDF Tools")
l = StringVar()
l2= StringVar()
f = StringVar()
e = StringVar()
filenamelabel = Label(textvariable=l).place(x=400, y=0)
filenamelabel2 = Label(textvariable=l2).place(x=400, y=25)
exportfolderlabel = Label(textvariable=f).place(x=400, y=50)
finalFileNameForm = Entry(gui).place(x=0, y=75)
def openFileDialog():
global fileName
fileName = filedialog.askopenfilename(initialdir = "/Users/", title="Pick a PDF file.", filetypes=(("pdf files","*.pdf"),("all files","*.*")))
l.set(fileName)
def openFileDialog2():
global fileName2
fileName2 = filedialog.askopenfilename(initialdir = "/Users/", title="Pick a second PDF file.", filetypes=(("pdf files","*.pdf"),("all files","*.*")))
l2.set(fileName2)
def openExportFolderDialog():
global exportFolder
exportFolder = filedialog.askdirectory(initialdir = "/Users/", title="Pick an export folder.")
f.set(exportFolder)
def append_pdf(input, output):
[output.addPage(input.getPage(page_num)) for page_num in range(input.numPages)]
def combinePdf():
output = PdfFileWriter()
append_pdf(PdfFileReader(file(fileName, "rb")),output)
append_pdf(PdfFileReader(file(fileName2, "rb")),output)
output.write(file(finalFileName, exportFolder))
importpdf1 = Button(text="Import PDF", command=openFileDialog).place(x=0, y=0)
importpdf2 = Button(text="Import PDF 2", command=openFileDialog2).place(x=0, y=25)
setexport = Button(text="Set Export Folder", command=openExportFolderDialog).place(x=0, y=50)
combinepdf = Button(text="Combine PDFs", command=combinePdf).place(x=0, y=100)
gui.mainloop()
當我運行的代碼,我得到的錯誤是
Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/init.py", line 1487, in call return self.func(*args) File "/Users/chris/Desktop/gui.py", line 43, in combinePdf append_pdf(PdfFileReader(file(fileName, "rb")),output) NameError: name 'file' is not defined
使用Python 3.4.1,Mac OS X小牛