View multiple PDF's one after another using tkPDFViewer

Viewed 43

I am having an issue with the tkPDFViewer library.

I want my code to basically create a slideshow of pdf's using tkinter. Right now my code adds each pdf to what's already there instead of removing the previous pdf. Please help me.

from tkPDFViewer import tkPDFViewer as pdf

destroy_list = []

def run():

    for thing in destroy_list:
        thing.pack_forget()
    try:
        v1.img_object_li.clear()
    except:
        pass
    item = Scans_List[0]   
    v2 = None
    v1 = None
    openfile = f"Scans\{item}"
    title_label.config(text = openfile)
    v1 = pdf.ShowPdf()
    v2 = v1.pdf_view(root, pdf_location = openfile, bar = False, width = 66, height = 90)
    v2.pack(side = "top", anchor = "e")
    destroy_list.append(v2)
    Scans_List.remove(item)
    root.after(5000, run)
    
run()
1 Answers

It is because v1 is a local variable inside run(), so v1.img_object_li.clear() always raise exception and cannot clear previous images.

One way to fix it is to pass v1 and v2 as arguments to run (they are None when it is first executed).

from itertools import cycle
...
# create a cycle list of PDF files
Scan_List = cycle([...])
...
# pass v1 and v2 as arguments and they are None initially
def run(v1=None, v2=None):
    if v1 and v2:
        v1.img_object_li.clear() # clear previous images
        v2.destroy() # destroy the previous PDF content
    item = next(Scans_List)  # get next PDF file in Scan_Listt
    openfile = f"Scans\{item}"
    title_label.config(text=openfile)
    v1 = pdf.ShowPdf()
    v2 = v1.pdf_view(root, pdf_location=openfile, bar=False, width=66, height=90)
    v2.pack(side="top", anchor="e")
    root.after(5000, run, v1, v2)

run()
...

Note that you can create v1 only once instead of creating it in every run():

...
# create v1 only once
v1 = pdf.ShowPdf()

def run(v2=None):
    if v2:
        v1.img_object_li.clear()
        v2.destroy()
    item = next(Scans_List)
    openfile = f"Scans\{item}"
    title_label.config(text=openfile)
    v2 = v1.pdf_view(root, pdf_location=openfile, bar=False, width=66, height=90)
    v2.pack(side = "top", anchor = "e")
    root.after(5000, run, v2)

run()
...
Related