PDF如何正确显示

2024-05-13 18:29:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码,它获取PDF文件,将页面转换为图像,然后将它们显示在ttk笔记本中。只有在我不使用函数加载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()


Tags: thetextfromimportpdfrootpagestab
1条回答
网友
1楼 · 发布于 2024-05-13 18:29:34

由于您使用了本地列表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

请注意,在填充图像之前,文本框已清除

相关问题 更多 >