Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Trình xem PDF cho Python Tkinter

Python nổi tiếng với thư viện lớn. Xử lý PDF dùng PyPDF2 xử lý, trích xuất, gộp trang, mã hóa PDF. Gói hữu ích quản lý luồng file như PDF. Dùng PyPDF2 tạo ứng dụng Tkinter đọc PDF bằng hộp thoại chọn file.

Các bước:

  • Cài yêu cầu: pip install PyPDF2 trong Shell. Import import Pypdf2.
  • Import filedialog tạo hộp thoại chọn file.
  • Tạo Text Widget thêm Menu: Open, Clear, Quit.
  • Định nghĩa hàm cho từng Menu.
  • Hàm mở file: đọc file bằng PdfFileReader(file). Trích xuất trang.
  • Chèn nội dung vào Text Box.
  • Hàm Quit Menu.

Ví dụ

#Import thư viện cần thiết
import PyPDF2
from tkinter import *
from tkinter import filedialog
#Tạo instance tkinter frame
win= Tk()
#Đặt Geometry
win.geometry("750x450")
#Tạo Text Box
text= Text(win,width= 80,height=30)
text.pack(pady=20)
#Hàm xóa text
def clear_text():
    text.delete(1.0, END)
#Hàm mở file pdf
def open_pdf():
    file= filedialog.askopenfilename(title="Select a PDF", filetype=(("PDF Files","*.pdf"),("All Files","*.*")))
    if file:
        pdf_file= PyPDF2.PdfFileReader(file)
        page= pdf_file.getPage(0)
        content=page.extractText()
        text.insert(1.0,content)
#Hàm thoát
def quit_app():
    win.destroy()
#Tạo Menu
my_menu= Menu(win)
win.config(menu=my_menu)
#Thêm dropdown
file_menu=Menu(my_menu,tearoff=False)
my_menu.add_cascade(label="File",menu= file_menu)
file_menu.add_command(label="Open",command=open_pdf)
file_menu.add_command(label="Clear",command=clear_text)
file_menu.add_command(label="Quit",command=quit_app)
win.mainloop()

Kết quả

Chạy mã hiển thị ứng dụng Tkinter đầy đủ. Chức năng mở file, xóa, thoát.

Trình xem PDF cho Python Tkinter

Bấm Menu "File" góc trái, mở PDF mới trong Text Box.

Trình xem PDF cho Python Tkinter