使用python实现调用Tkinter窗口选择照片文件,并将选中的照片转换成PDF格式,文件将根据照片数量输出单个的PDF文件;
效果
源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 from tkinter import filedialogimport tkinter as tkfrom reportlab.lib.pagesizes import portraitfrom reportlab.pdfgen import canvasfrom PIL import Imageimport osroot = tk.Tk() root.title("照片转PDF" ) root.geometry('400x300+{}+{}' .format (int ((root.winfo_screenwidth() - 400 ) / 2 ), int ((root.winfo_screenheight() - 300 ) / 2 ))) copyright_label = tk.Label(root, text="© 2023 嗜血星空earth" , font=("微软雅黑" , 8 )) copyright_label.place(relx=0.5 , rely=1 , anchor='s' ) explain_label = tk.Label(root, text="说明:本程序用于将多张照片转换为单个PDF文件。选择一个或多个照片文件后,程序将自动创建同样数量的PDF文件。" , font=("微软雅黑" , 10 ), wraplength=350 ) explain_label.pack(pady=20 ) file_label = tk.Label(root, text="未选择任何文件。" ) file_label.pack(pady=(10 , 0 )) def select_file (): file_paths = filedialog.askopenfilenames(title='请选择要转换的照片文件' , filetypes=[('Image files' , '*.jpg;*.png' )]) if file_paths: file_label.config(text=f"已选择 {len (file_paths)} 个文件。" ) for image_path in file_paths: image = Image.open (image_path) width, height = image.size path, filename_ext = os.path.splitext(image_path) pdf_path = path + ".pdf" c = canvas.Canvas(pdf_path, pagesize=portrait((width, height))) c.setPageSize(portrait((width, height))) c.drawImage(image_path, 0 , 0 , width, height) c.save() print ("PDF 文件已生成。" ) else : file_label.config(text="未选择任何文件。" ) select_button = tk.Button(root, text="选择文件" , command=select_file) select_button.pack(pady=(10 , 20 )) root.mainloop()
封装 py文件打包成exe文件便于后期使用;
1 pyinstaller -F --noconsole --hidden-import tkinter main.py