tkPDFViewer 只工作一次然后抛出:图像 "pyimage1" 不存在

tkPDFViewer working only once then throw : image "pyimage1" doesn't exist

# Importing tkinter to make gui in python
from tkinter import*
  
# Importing tkPDFViewer to place pdf file in gui.
# In tkPDFViewer library there is
# an tkPDFViewer module. That I have imported as pdf
from tkPDFViewer import tkPDFViewer as pdf
  
v2= NONE
# Initializing tk
root = Tk()
  
# Set the width and height of our root window.
root.geometry("550x750")
  
# creating object of ShowPdf from tkPDFViewer.
v1 = pdf.ShowPdf()
  
# Adding pdf location and width and height.
v2 = v1.pdf_view(root,
                 pdf_location = r"YourPdfFile.pdf", 
                 width = 50, height = 100)
  
# Placing Pdf in my gui.
v2.pack()
root.mainloop()

如何重现错误:

  1. 运行上面的代码一次,它会在window.
  2. 中显示.PDF
  3. 关闭 Window.
  4. 运行 再次代码
  5. 然后你会遇到以下问题:

.

Exception in thread Thread-10:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tkpdfviewer-0.1-py3.9.egg\tkPDFViewer\tkPDFViewer.py", line 61, in add_img
  File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 3728, in image_create
    return self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist

有人知道我该如何解决这个问题吗?

tkPDFViewer 使用 class 变量 img_object_li(类型 list)存储从 PDF 文件中提取的图像。当你执行spyder中的脚本时,classtkPDFViewer的实例即使在tkinterwindow关闭后仍然存在于spyder内核中。

所以下一次执行脚本时,之前的图像实例仍然存储在 class 变量 img_object_li 中,它们将被再次使用和显示,这引发了异常,因为之前的Tk() 实例被销毁。

要解决此问题,在加载 PDF 文件之前应清除 class 变量 img_object_li

# Importing tkinter to make gui in python
from tkinter import*
  
# Importing tkPDFViewer to place pdf file in gui.
# In tkPDFViewer library there is
# an tkPDFViewer module. That I have imported as pdf
from tkPDFViewer import tkPDFViewer as pdf
  
v2= NONE
# Initializing tk
root = Tk()
  
# Set the width and height of our root window.
root.geometry("550x750")
  
# creating object of ShowPdf from tkPDFViewer.
v1 = pdf.ShowPdf()

### clear the image list ###
v1.img_object_li.clear()
  
# Adding pdf location and width and height.
v2 = v1.pdf_view(root,
                 pdf_location = r"test.pdf", 
                 width = 50, height = 100)
  
# Placing Pdf in my gui.
v2.pack()
root.mainloop()