PDF如何正确显示

PDF how showing up properly

我有这个简单的代码,可以获取 PDF,将页面转换为图像,然后将它们显示在 ttk Notebook 中。这仅在我不使用函数加载 PDF 时有效。然而,这是列出许多 PDF 表单的更大程序的一部分;因此,我需要一个函数来加载 PDF。 PDF 似乎正在加载,但全是灰色的。

我不知道我做错了什么。我环顾四周,但找不到与我 运行 遇到的确切问题相关的任何内容。我确实想使用这种显示 PDF 表单的方法,因为当 PDF 表单填写信息时,它看起来最好。

请多多包涵,因为我一个月前才开始编程。我的代码可能有不止一处错误。

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from pdf2image import convert_from_path


def upload_pdf():

    # PDF is converted to a list of images
    pages = convert_from_path('/home/admin/PycharmProjects/ChecklistProject/Main_Genny_Bi-monthly_Operational_Check_M72QZZ1.pdf', size=(800, 900))

    # Empty list for storing images
    photos = []

    # Storing the converted images into list
    for i in range(len(pages)):
        photos.append(ImageTk.PhotoImage(pages[i]))

    # Adding all the images to the text widget
    for photo in photos:
        pdf.image_create(tk.END, image=photo)

        # For Separating the pages
        pdf.insert(tk.END, '\n\n')


root = tk.Tk()
root.title('')
root.geometry("920x680+500+20")
mon_width = root.winfo_screenwidth()
mon_height = root.winfo_screenheight()

tab_control = ttk.Notebook(root)
tab_control.place(x=10, y=10, height=625, width=800)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)

tab_control.add(tab1, text="Preview pdf")
tab_control.add(tab2, text="Other")

# ------- pdf text box with scroll bar

scroll_y = tk.Scrollbar(tab1, orient=tk.VERTICAL)

pdf = tk.Text(tab1, yscrollcommand=scroll_y.set, bg="grey")

scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
scroll_y.config(command=pdf.yview)

pdf.pack(fill=tk.BOTH, expand=1)

# ------- button -----------------------------

my_button = tk.Button(root, text="Upload", command=upload_pdf)
my_button.place(x=840, y=400)

root.mainloop()

由于您使用本地列表 photos 来存储 ImageTk.PhotoImage() 的实例,它们将在函数完成后被垃圾回收。

您可以将 photos 声明为全局变量或使用 pdf 的属性来存储 photos 的引用:

def upload_pdf():
    # PDF is converted to a list of images
    pages = convert_from_path('/home/admin/PycharmProjects/ChecklistProject/Main_Genny_Bi-monthly_Operational_Check_M72QZZ1.pdf', size=(800, 900))

    # Empty list for storing images
    photos = []

    # Storing the converted images into list
    for i in range(len(pages)):
        photos.append(ImageTk.PhotoImage(pages[i]))

    # Clear the text box
    pdf.delete('1.0', tk.END)

    # Adding all the images to the text widget
    for photo in photos:
        pdf.image_create(tk.END, image=photo)

        # For Separating the pages
        pdf.insert(tk.END, '\n\n')

    pdf.photos = photos  # used an attribute of "pdf" to store the references

请注意,在填充图像之前文本框是清晰的。