我是 TKinter 新手,似乎找不到任何关于如何在窗口中查看文档的示例。我要完成的工作是,选择PDF或TIF时,它将打开文件并使用TKINTER在窗口中显示第一页。这可能吗?
4 回答
不,不可能在 Tkinter 窗口中显示 TIF 或 PDF。您的主要选项是显示纯文本和显示图像(带有纯 Tkinter 的 .gif,如果您包含 PIL - python 图像库,则为其他格式)。
没有什么是不可能的,我的朋友!
尝试使用以下代码片段: http: //nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html 将 pdf 转换为图像。然后我会使用 PIL 和 Tkinter 在标签上显示图像。
而且我认为 Tif 文件应该毫无问题地显示在标签上 IIRC。
自发布此问题以来已经过去了很长时间,但是对于那些仍在寻找解决方案的人,这是我发现的一个:
https://github.com/rk700/PyMuPDF/wiki/Demo:-GUI-script-to-display-a-PDF-using-wxPython-or-Tkinter
基本上,它使用 PyMuPDF,一个用于 MuPDF 的 python 绑定。MuPDF 是一个轻量级的文档查看器,能够显示一些文件格式,例如 pdf 和 epub。
我引用了用于 TKinter 的代码:
这个演示可以很容易地被 Tkinter 采用。你需要进口
from Tkinter import Tk, Canvas, Frame, BOTH, NW
from PIL import Image, ImageTk
并执行以下操作以显示每个 PDF 页面图像:
#-----------------------------------------------------------------
# MuPDF code
#-----------------------------------------------------------------
pix = doc.getPagePixmap(pno - 1) # create pixmap for a page
#-----------------------------------------------------------------
# Tkinter code
#-----------------------------------------------------------------
self.img = Image.frombytes("RGBA",
[pix.width, pix.height],
str(pix.samples))
self.photo = ImageTk.PhotoImage(self.img)
canvas = Canvas(self, width=self.img.size[0]+20,
height=self.img.size[1]+20)
canvas.create_image(10, 10, anchor=NW, image=self.photo)
canvas.pack(fill=BOTH, expand=1)
以下代码使用旧库pypdfocr
(我必须修改它以使用 Python 3)和Ghostscript(Ghostscript 需要在 Python 之外安装,因此不适合分发软件)将每个 PDF 页面转换为然后可以由 PIL 打开的图像。从它使用非常旧的库和包的意义上说,DrD 的答案可能更合适。
import glob
import PIL.Image
import PIL.ImageTk
import pypdfocr.pypdfocr_gs as pdfImg
files = glob.glob(pdfImg.PyGs({}).make_img_from_pdf(file_name)[1])
pages = [PIL.ImageTk.PhotoImage(PIL.Image.open(file)) for file in files]