我的工作是使用 tkinter 自动一页一页地显示 pdf 文件的页面。为此,我为每个页面创建一个图像并将所有图像存储在一个列表中。我可以通过手动滚动显示列表中的所有页面。但我希望它是自动的(自动滚动)。我该如何继续?
这是我的代码:
import os,ironpdf,time
import shutil
from tkinter import *
from PIL import Image,ImageTk
def do_nothing():
print("No thing")
def convert_pdf_to_image(pdf_file):
pdf = ironpdf.PdfDocument.FromFile(pdf_file)
#Extrat all pages to a folder as image files
folder_path = "images"
pdf.RasterizeToImageFiles(os.path.join(folder_path,"*.png"))
#List to store the image paths
image_paths = []
#Get the list of image files in the folder
for filename in os.listdir(folder_path):
if filename.lower().endswith((".png",".jpg",".jpeg",".gif")):
image_paths.append(os.path.join(folder_path,filename))
return image_paths
def on_closing():
#Delete the images in the 'images' folder
shutil.rmtree("images")
window.destroy()
window = Tk()
window.title("PDF Viewer")
window.geometry("1900x800")
canvas = Canvas(window)
canvas.pack(side=LEFT,fill=BOTH,expand=True)
canvas.configure(background="black")
scrollbar = Scrollbar(window,command=canvas.yview)
scrollbar.pack(side=RIGHT,fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind("<Configure>",lambda e:canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<MouseWheel>",lambda e:canvas.yview_scroll(int(-1*(e.delta/120)),"units"))
frame = Frame(canvas)
canvas.create_window((0,0),window=frame,anchor="nw")
images = convert_pdf_to_image("input.pdf")
for image_path in images:
print(image_path)
image = Image.open(image_path)
photo = ImageTk.PhotoImage(image,size=1200)
label = Label(frame,image=photo)
label.image = photo
label.pack(fill=BOTH)
time.sleep(1)
window.mainloop()
您只需使用
canvas.yview_scroll()
定期调用 .after()
:
...
def auto_scroll():
canvas.yview_scroll(1, "units")
# change 1000 to other value that suits your requirement
canvas.after(1000, auto_scroll) # scroll the images every second
auto_scroll() # start the auto scrolling
window.mainloop()