简介
在这篇博客中,我们将深入分析一个基于 wxPython 实现的 PDF 阅读器程序。该程序支持加载 PDF 文件并显示页面内容,同时支持页面切换动画效果。
主要功能包括:
- 加载 PDF 文件
- 显示当前页面
- 上一页/下一页切换
- 页面切换动画
C:\pythoncode\new\pdfreader.py
全部代码
import wx
import fitz # PyMuPDF
from PIL import Image
import time
class PDFReader(wx.Frame):
def __init__(self, parent, title):
super(PDFReader, self).__init__(parent, title=title, size=(800, 600))
self.current_page = 0
self.doc = None
self.page_images = []
self.animation_offset = 0
self.is_animating = False
self.animation_direction = 0
self.next_page_idx = 0
self.init_ui()
self.init_timer()
def init_ui(self):
self.panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# 创建工具栏
toolbar = wx.BoxSizer(wx.HORIZONTAL)
open_btn = wx.Button(self.panel, label='打开PDF')
prev_btn = wx.Button(self.panel, label='上一页')
next_btn = wx.Button(self.panel, label='下一页')
open_btn.Bind(wx.EVT_BUTTON, self.on_open)
prev_btn.Bind(wx.EVT_BUTTON, self.on_prev_page)
next_btn.Bind(wx.EVT_BUTTON, self.on_next_page)
toolbar.Add(open_btn, 0, wx.ALL, 5)
toolbar.Add(prev_btn, 0, wx.ALL, 5)
toolbar.Add(next_btn, 0, wx.ALL, 5)
self.pdf_panel = wx.Panel(self.panel)
self.pdf_panel.SetBackgroundColour(wx.WHITE)
self.pdf_panel.Bind(wx.EVT_PAINT, self.on_paint)
vbox.Add(toolbar, 0, wx.EXPAND)
vbox.Add(self.pdf_panel, 1, wx.EXPAND | wx.ALL, 5)
self.panel.SetSizer(vbox)
self.Centre()
def init_timer(self):
# 创建定时器用于动画
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_timer)
def on_open(self, event):
with wx.FileDialog(self, "选择PDF文件"