我对tkPDFViewer库有个问题。
我希望我的代码基本上创建一个幻灯片的pdf使用tkinter。现在,我的代码将每个pdf添加到已经存在的内容中,而不是删除之前的pdf。请帮帮我。
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()发布于 2022-07-02 14:50:19
这是因为v1是run()中的一个局部变量,因此v1.img_object_li.clear()总是引发异常,无法清除以前的图像。
修复该问题的一种方法是将v1和v2作为要运行的参数传递(第一次执行时它们是None )。
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()
...请注意,您只能创建v1一次,而不是在每个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()
...https://stackoverflow.com/questions/72831526
复制相似问题