How to automatically scroll (autoscroll) a list of images contained in a list with tkinter

40 Views Asked by At

My job is to automatically display, one by one, the pages of a pdf file with tkinter. To do this, I create an image for each page and store all the images in a list. I can display all the pages from my list with manual scrolling. But I want it to be automatic (autoscroll). How can I proceed?
Here is my code:

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()
1

There are 1 best solutions below

0
acw1668 On

You can simply call canvas.yview_scroll() periodically using .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()